I have been using Template Design pattern in my code for implementing CRUD procedures for different resources.
There are some steps which are same for many resources and some which need some addition/overriding.
ResourceCommonProcedures as a base class and each Resource procedure inheriting the base class.
public class ResourceCommonProcedures {
public Response create(Request request){
Response response = new Response();
int resType = this.getResourceType(request);
ResourceCommonProcedures rp = getResourceController(resType);
response = rp.create(request);
return response;
}
private ResourceCommonProcedures getResourceController(int resourceType){
//..
switch(resourceTypeName){
case Resource1:
return new R1Procedures();
case Resource2:
return new R2Procedures();
case Resource3:
return new R3Procedures();
...............
}
}
Class R1Procedures extends ResourceCommonProcedures{
public Response create(Request request) {
Response response = new Response();
Resource1 resource = (Resource1) request.getContent();
...........
// Converts DB structure to JPA
R1Converter r1Converter = new R1Converter();
Resource1JPA resourceJpa = r1Converter.toJPA(resource);
dao.persist();
return response;
}
}
Class R2Procedures extends ResourceCommonProcedures{
public Response create(Request request) {
Response response = new Response();
Resource1 resource = (Resource2) request.getContent();
// SOME RESOURCE 2 SPECIFIC CODE
...........
// Converts DB structure to JPA
R2Converter r2Converter = new R2Converter();
Resource2JPA resourceJpa = r2Converter.toJPA(resource);
dao.persist();
return response;
}
As Joshua Bloch wrote in the third edition of Effective Java,
The Template Method pattern [..] is far less attractive. The modern alternative is to provide a static factory or constructor that accepts a function object to achieve the same effect.
I feel the code reuse in 10-15 resources procedures I am writing is significant. Shall Template design pattern be avoided due to Inheritance ?