Thursday, July 26, 2012

Builder Pattern and Template Method Pattern


Builder pattern is one pattern that belongs to the category of Creational Pattern.  It is used to  create the object for the client.  There are some situation where  the object creation is to be done via multiple steps.  Builder pattern comes up for this situations.   With Builder pattern you can have the fine-grained control over the some steps in the creation process.

In the below example to make a policy object it needs several steps: intializePolicy, addProduct and calculateDiscount.  After these three steps one policy objects can be constructed completely.   For different Policy classes you may be able to differentiate the each step creation in the concrete policy maker classes.   Here NZPolicyMaker will make the NZPolicy and AusPolicyMaker will make the AusPolicy.  In each step you can decide what to do based on the requirement for NZPolicy or AustPolicy.

So in short, Builder pattern applies to the situation where one object creation is multiple predefined steps and you can have the control over each steps in concrete Builder based on the requirement.


Template method pattern is another category of design pattern.  It belongs to Behavioural pattern.  This pattern is used to implement one algorithm which is executed in multiple steps and the interface defines the skeleton of the algorithm while the concrete class can implement the steps which vary.

The below is one example of Template method pattern.  The interface FleetCardHandler defines the methods to be used to process the request message from the fleet card.   But different fleet cards need the different processing logic.  These varying logic are implemented in the concrete classes: SUCFleetCardHanlder and TekFleetCardHandler.

From here we can see the similarity between Builder pattern and Template method pattern.  Both these patterns have the predefined steps to perform one process(creation or  algorithm) and these steps can be implemented based on the varying business logic.  Builder and Template Method pattern give you the fine-grained control over the either creation or algorithm.