Behavorial Patterns - Template Method Pattern


  1. An abstract class is a perfect example of a template method pattern. 
  2. Template method is one of the concrete methods in an abstract class which defines the order of method calls.         
  3. Other concrete methods are common implementations which will not be varied in subclasses.        
  4. Methods which require specific implementations will be marked as abstract and delegated to implementations        
Here, Service method in AbstractRequestController defines the order of authenticate(), parse() and prepareResponse() method calls. Concrete methods  authenticate(), parseRequest() methods has common implementations which subclasses can reuse without overriding. prepareResponse() implementation is delegated to extending classes since its implementation varies for each implementation such as Web, REST. 

public abstract class AbstractRequestController{

    void service(HttpServletRequest request, HttpServletResponse response){
        try{
            authenticate(request);
        }catch(AuthenticationException ae){
            response.setStatusCode(404);
        } 
        HashMap requestParams = parseRequest(request);
        prepareResponse();
    }

    public void authenticate(HttpServletRequest request){
        ...
    }   
    public void parseRequest(HttpServletRequest request){
        ...
    }

    abstract void prepareResponse();
}

class WebRequestController{
    public void prepareResponse(){//Prepare HTML response}
}

class RestRequestController{
    public void prepareResponse(){//Prepare JSON response}
}



Comments

Popular posts from this blog

Distributed database design using CAP theorem

SQL Analytical Functions - Partition by (to split resultset into groups)

Easy approach to work with files in Java - Java NIO(New input output)