* Adding support for maven assembly plugin to generate executable jar with all dependencies in built * Merge branch 'master' into issue-989 # Conflicts: # abstract-document/pom.xml # pom.xml * Adding maven assemly plugin for projects with name A * Update in format as per checkstyle, i.e. Spcae in place of tab with size of 2 * batch set - 2 having all project with B and C * issue-989 d-e-f * fixing eip pom and adding g-h-i-l-m-n Skipping naked object as it seems it doesn't have main method, will consider this at end * Adding for O and P projects Skipping Object-Mother as we don't have main method for same. * Final batch
layout, title, folder, permalink, categories, tags
layout | title | folder | permalink | categories | tags | |
---|---|---|---|---|---|---|
pattern | Template method | template-method | /patterns/template-method/ | Behavioral |
|
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 changing the algorithm's structure.
To make sure that subclasses don’t override the template method, the template method should be declared final
.
Class diagram
Applicability
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
- When common behavior among subclasses should be factored and localized in a common class to avoid code duplication. This is good example of "refactoring to generalize" as described by Opdyke and Johnson. You first identify the differences in the existing code and then separate the differences into new operations. Finally, you replace the differing code with a template method that calls one of these new operations
- To control subclasses extensions. You can define a template method that calls "hook" operations at specific points, thereby permitting extensions only at those points
Tutorial
Real world examples
- javax.servlet.GenericServlet.init:
Method
GenericServlet.init(ServletConfig config)
calls the parameterless methodGenericServlet.init()
which is intended to be overridden in subclasses. MethodGenericServlet.init(ServletConfig config)
is the template method in this example.