Template method design pattern in java

CodeProjectTemplate method pattern is a behavioral design pattern which provide base method for algorithm,called template method which defers some of its steps to subclasses So algorithm structure is same but some of its steps can be redefined by subclasses according to context.

Template means Preset format like HTML templates which has fixed preset format.Similarly in template method pattern,we have a preset structure method called template method which consists of steps.This steps can be abstract method which will be implemented by its subclasses.

So in short you can say,In template method pattern,there is template method which defines set of steps and implementation of steps can be deferred to subclasses.Thus template method defines algorithm but exact steps can be defined in subclasses.

When to use it:

  • When you have a preset format or steps for algorithm but implementation of steps may vary.
  • When you want to avoid code duplication,implementing common code in base class and variation in subclass.

Structure:

So in above diagram,as you can see we have defined template method with three steps i.e. operation1,operation2 and operation3.Among them,opeation1 and operation2 are abstract steps,so these are implemented by ConcreteClass.We have implemented operation3 here.You can implement an operation in base class in two scenario first is if it is common to all and second is if it is default implementation of that method.
UML diagram will be much clearer now.

Components:

AbstractClass
  • It defines template method defining the structure of algorithm.
  • It also defines abstract operations that will be implemented by subclasses to define steps of algorithm.

ConcreteClass

  • It implements abstract operation of super class to carry out subclass specific steps of the algorithm and also overrides operation if default behavior is not required

Important points about template method pattern:

  • Template method in super class follows “the Hollywood principle”: “Don’t call us, we’ll call you”. This refers to the fact that instead of calling the methods from base class in the subclasses, the methods from subclass are called in the template method from superclass.
  • Template method in super class should not be overriden so make it final
  • Customization hooks:Methods containing a default implementation that may be overidden in other  classes are called hooks methods. Hook methods are intended to be overridden, concrete methods are not.So in this pattern,we can provide hooks methods.The problem is sometimes it becomes very hard to differentiate between hook methods and concrete methods.
  • Template methods are technique for code reuse because with this,you can figure out common behavior and defer specific behavior to subclasses.

Example:

Lets take example.When you have to read from two data source i.e CSV and database then you have to process that data and generate output as CSV files.Here three steps are involved.

  1. Read data from correspoding data source
  2. Process data
  3. Write output to CSV files

Java code:

Below class contains template method called “parseDataAndGenerateOutput” which consists of steps for reading data,processing data and writing to csv file.

1.DataParser.java

In below class,CSV specific steps are implement in this class
2.CSVDataParser.java
In below class,database specific steps are implement in this class
 
3.DatabaseDataParser.java
4.TemplateMethodMain.java
output:

Used in java API:

Source code:

Source:Download

Related Posts

  • 25 April

    Strategy design pattern in java

    Table of ContentsStrategy design pattern exampleStrategy pattern example In this post, we will see about Strategy design pattern in java. Strategy design pattern allows us to change algorithm implementation at runtime.Strategy design pattern provides multiple algorithms and client can choose algorithm based on their needs with the help of composition. Strategy design pattern example Let’s […]

  • 24 April

    Singleton design pattern in java

    Table of ContentsSingleton classEager initializationLazy initializationThread safe SingletonDouble check lockingBill Pugh Singleton ImplementationCreate singleton using EnumTesting singleton with ReflectionTesting singleton with SerializationTesting singleton with Cloning. In this post, we will see about Singleton design pattern in java. Singleton design pattern is one of the simplest design pattern but singleton property can be broken using multithreading, […]

  • 14 July

    How to use connection pool using service locator design Pattern in java

    In this post, you will learn about the Connection Pool. This post is intended by java application development experts for entire development community to let people learn and acknowledge about Connection Pool and how to use its object using Service Locator design pattern. Introduction Connection pool is a mechanism which applicable for all technologies in […]

  • 27 February

    Observer design pattern in java

    Table of ContentsWhen to use it: UML diagram for observer design pattern:Components:Java in-built API for observer pattern:Example:Using java inbuilt APIs:Some important points about observer pattern:Source code: As the name suggests it is used for observing some objects.Observer watch for any change in state or property of subject.Suppose you are interested in particular object and want to […]

  • 29 September

    Builder design pattern in java

    Table of ContentsGeneric UML diagram for builder design pattern:Elements:When to use it:WorkFlow:Example: Builder design pattern allows to create complex object step by step and also enforces a process to create an object as a finished product.Construction of object should be such that same construction process can create different representations.Director controls the construction of object and […]

  • 28 September

    Proxy design pattern in java

    Table of ContentsWhen to use it:UML diagram for proxy design pattern:Elements:WorkFlow:Example:Source code: CodeProjectProxy design pattern allows you to create a wrapper class over real object.Wrapper class which is proxy,controls access to real object so in turn you can add extra functionalities to real object without changing real object’s code. As described by GoF: “Provide a […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.