Template Method Design Pattern by Example

This post explains Template Design Pattern using a simple example.

When to Use ?  – When you know the steps of an algorithm and order in which they should be performed, but don’t know how to perform all of the steps or implementations of the steps vary from user to user. This pattern is the solution for algorithm implementation where invocation order of steps is fixed, but steps implementation may vary for example getting data from database or file system etc.

How to Use ? – Encapsulate all individual steps steps we don’t know how to perform as abstract methods in an super abstract class and provide a final method that invokes steps in correct order. Concrete subclasses of this super abstract class implement the abstract methods that performs individual steps. They concept is that super class controls invocation order of the steps and leave implementation of these steps up to end user.

      When implementing the Template Method pattern, the abstract class must factor out those methods that may change between subclasses and ensure that the method signature enable sufficient flexibility in implementation.

An Example – Here is the simple order processing code, which process given order using individual steps.

Super Abstract Class -

package templatemethod;

import java.util.List;
import sun.security.util.Password;

public abstract class ProcessOrderTemplate {
    public ProcessOrderTemplate() {
    }
    private Order order;
    /**
     * Steps to process order
     */
    public abstract boolean  validateCustomer(String custName, int custId);
    public abstract boolean checkAvailibility(List items);
    public abstract boolean checkShipping(String shippingAdd);
    public abstract boolean generateInvoice(Order order);
    public abstract boolean sendNotification();
    public abstract boolean placeOrder(Order order);
    /**
     * Algoritm to process order.
     * Here is the step wise processing of order
     * @param order
     * @return
     */
    public final String procesOrder(Order order){
        String status = "TRUE";
        if(validateCustomer(order.getCustomerName(),order.getCustomerId())){
            status = "Customer Information not Found";
        }
        if(checkAvailibility(order.getItems())){
            status="Items are not available";
        }
        if(checkShipping(order.getShipAdd())){
            status="Shipping is not available";
        }
        generateInvoice(order);
        placeOrder(order);
        sendNotification();
        return status;
    }
}

      In this example abstract class ProcessOrderTemplate implements the business logic , which include checking customer,shipping address , availibility etc. This processOrder method is final, so that this logic can’t be modified by subclasses.

SubClass -

package templatemethod;

import java.util.List;

public class ProcessOrderTemplateImpl extends ProcessOrderTemplate{
    public ProcessOrderTemplateImpl() {
    }

    public boolean validateCustomer(String custName, int custId) {
        //...
        return true;
    }

    public boolean checkAvailibility(List items) {
        //..
        return true;
    }

    public boolean checkShipping(String shippingAdd) {
        //...
        return true;
    }

    public boolean generateInvoice(Order order) {
        //..
        return true;
    }

    public boolean sendNotification() {
        //..
        return true;
    }

    public boolean placeOrder(Order order) {
        //...
        return true;
    }
    /**
     * Invoking Super class method to process the order
     * @param args
     */
    public static void main(String[] args) {
        new ProcessOrderTemplateImpl().procesOrder(new Order());
    }
}

SubClass of ProcessOrderTemplate needs to implement four abstract methods from super class. They don’t need to concern about business logic. It is concern about implementation of steps ( abstract methods) , for example one might implement these methods using JDBC, while another might implement then using SQLJ or JDO.

 

Such uses of Template Method pattern offers good separation of business logic from implementing primitive operation. As template methods are protected, rather than public, callers spared the details of the class’s implementation.

Comments

Post a Comment

Popular posts from this blog

State Design Pattern by Example

Eclipse command framework core expression: Property tester

Composite Design Pattern by example