April 30, 2014

Design Patterns - Template Method Pattern


  • Needs for defining the outline of an algorithm and let subclasses do some work. 
  • Needs for providing a fundamental method for code reuse that allows subclasses to specify behaviors.


  • Define the skeleton of an algorithm in an operation, deferring some steps to sub-classes. 
  • Let  sub-classes  redefine certain  steps  of  an  algorithm without changing the algorithm's structure.


    Template Method Pattern UML Class Diagram
    Template Method Pattern UML Class Diagram

  • Abstract class contains the template method and provides a framework that concrete classes can be plugged into.
  • Template method defines an algorithm in terms of abstract operations that subclasses override to provide concrete behavior.
  • The ConreteClass implements the abstract operations which are called when the template method needs them.

Implementation in Java

abstract class AbstractClass {

  final void templateMethod() {

  final void concreteOperation() {
    //a concrete implementation

  abstract void operation1(); // abstract operations, must be implemented by sub-classes

  abstract void operation2();

  void hook() {
   // default implementation, subclasses are free to override 

When we look at the above code, there are four different types of methods used in the parent AbstractClass: 
  • Concrete methods
    These methods maybe used in the template method directly or used by subclasses. Concrete methods are not intended to be overridden so it's modified with final.
  • Abstract methods
    These methods that must be implemented by subclasses.
  • Hook methods
    These methods give subclasses the ability to "hook into" the algorithm at various points if they wish, a subclass is also free to ignore the hook.
  • Template methods
    The template method defines the order of operations each defined by a method listed above.

Hollywood Principle

  The Hollywood Principle (Don't call us, we'll call you) avoids low level components depending on high level components, and instead allows low level classes (ConcreteClass) a way of hooking into the parent class (AbstractClass). The Template Method pattern makes use of the Hollywood Principle. When we design the Template Method Pattern we are telling subclasses, "don't call us, we'll call you". The template method in the abstract class controls the overall process, "calling" subclass methods when necessary. Subclasses never call the abstract class directly without being "called" first. Subclasses simply provides implementation details.

JDK Implementations 

  • javax.swing.JFrame#paint(Graphics g)
  • java.applet.Applet#init(), #start(), #stop(), #destroy(), #paint(Graphics g)
  • java.util.Collections#sort()

Related Patterns

  • The Strategy and Template Method Patterns both encapsulate algorithms, one by inheritance and one by composition.
  • The Factory Method is a specialization of Template Method.