JAVA Means DURGA SOFT
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 1
JAVA Means DURGA SOFT
Template Method Design Pattern
If we take a look at the dictionary definition of a template we can see that a template is
a preset format, used as a starting point for a particular application so that the format does not
have to be recreated each time it is used. On the same idea is the template method is based. A
template method defines an algorithm in a base class using abstract operations that subclasses
override to provide concrete behavior.
Problem: Remembering multiple method names and their sequence of invocation that are
required to complete certain task is complex and error prone process.
Solution: Work with Template Method design pattern, where one java method definition
contains all the multiple method calls in a sequence. So programmer needs to call only one java
method to complete the task.
Intent:
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
Template Method lets subclasses redefine certain steps of an algorithm without letting
them to change the algorithm's structure.
Application Areas: The Template Method pattern should be used:
To implement the invariant parts of an algorithm once and leave it up to subclasses to
implement the behavior that can vary.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 2
JAVA Means DURGA SOFT
When refactoring is performed and common behavior is identified among classes. A
abstract base class containing all the common code (in the template method) should be
created to avoid code duplication.
An application framework allows you to inherit from a class or set of classes and create a
new Application, reusing most of the code in the existing classes and overriding one or more
methods in order to customize the application to your needs. A fundamental concept in the
application framework is the Template Method which is typically hidden beneath the covers
and drives the application by calling the various methods in the base class (some of which you
have overridden in order to create the application).
For Ex, the process() method of predefined RequestProcessor class (in Struts 1.X) is
Template Method because it internally calls 16+ processXxx() methods in a sequence to
complete the task (processing the request i.e. trapped by the ActionServlet).
An important characteristic of the Template Method is that it is defined in the base class
and cannot be changed. It’s sometimes a private method but it’s virtually always final. It calls
other base-class methods (the ones you override) in order to do its job, but it is usually called
only as part of an initialization process (and thus the client programmer isn’t necessarily able to
call it directly).
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 3