Monday, May 23, 2016

Template method design pattern


This design pattern comes under behavioral design pattern

Definition
Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
Basically base class defines the Placeholders, skeleton of the operation and derived classes implement those Placeholders as necessary.

UML Diagram 







Main components of the design pattern
AbstractClass  - The base class
All the abstract primitive operations are defined here

A template method which defines skeleton/structure of the algorithm. This method calls the primitive operations and other necessary methods which resides in the abstract class.

ConcreteClass – Sub class
Implements the abstract operations which defined in the base abstract class as needed

Usage

Mostly using when creating frameworks. A framework normally has multiple steps (Placeholders) and finally they all call by a base method. Those steps can be overridden in different ways in different scenarios.  But that base method is common to all scenarios and it should be a final method which is no one can override it.
All reusable code is declared in the framework's base classes, and then clients of the framework are free to do customizations by creating derived classes as needed.

Example

Think, that we are going to implement a common database access class which can be used to retrieve data from multiple database servers like “SQL Server”, “MySql”, “Oracle” and Etc.





Abstract class = DataAccess
Template Method = RunQuery() -
Abstact Methods = OpenConnection(), OpenTransaction(), ProcessQuery(),EndTransaction(),CloseConnection()
Concreate Classes = SQLDataAccess , MySQLDataAccess  - All the above abstract methods must implement on these concreate classes


DataAccess Class - Base Class



SQLDataAccess Class


MySQLDataAccess Class
    


When to implement template method

A template pattern should be used when there is an algorithm with many implementations but when we can find significant similarity among them. Simply where a number of components/scenarios shared the same process but the implementation was slightly different from each other.
Sometimes Template method referred as “The Hollywood principle”, when we think from the superclass point of view simply it means “Don’t call us, we will call you”.  That means instead of calling the methods from base class in the subclasses, the methods from the subclass are called by the template method in base class. Hence the template method implemented by the base class should not be overridden. So the Template method in the base class should be a “Final“and non-abstract method.