The 23 GoF design patterns and Dependency Injection – choose a pattern Abstract Factory design patternBuilder design patternFactory Method design patternPrototype design patternSingleton design patternAdapter design patternBridge design patternComposite design patternDecorator design patternFacade design patternFlyweight design patternProxy design patternChain of Responsibility design patternCommand design patternInterpreter design patternIterator design patternMediator design patternMemento design patternObserver design patternState design patternStrategy design patternTemplate Method design patternVisitor design patternDependency Injection design pattern

Template Method Design Pattern

Behavioral pattern. Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects.

The Template Method design pattern solves problems like: How can the invariant parts of a behavior be implemented once so that subclasses can implement the variant parts?

Open in the interactive referenceDownload the PDF reference

Problem

The Template Method design pattern solves problems like:
How can the invariant parts of a behavior be implemented once
so that subclasses can implement the variant parts?
How can subclasses redefine certain parts of a behavior
without changing the behavior's structure?
See Applicability section for all problems Template Method can solve. See Solution section for how Template Method solves the problems.

  • The standard way is to define subclasses (SubClass1|operation()) that redefine the behavior of a parent class (Class|operation()).
  • This makes it impossible to redefine only certain parts of the behavior independently from (without having to duplicate) the other parts.
  • That's the kind of approach to avoid if we want that subclasses can redefine only certain parts of a behavior without changing the other parts or the structure of the behavior.
  • For example, designing reusable classes.
    It should be possible that a class implements the common (invariant) parts of a behavior and let users of the class write subclasses to redefine the variant parts to suit their needs. But subclasses should not be able to change anything else.
  • For example, enforcing invariant parts of a behavior.
    A behavior often requires invariant functionality to be performed before and/or after its core functionality (for example, for setting up and resetting state).
    It should be possible to redefine only the core functionality without changing the invariant functionality.

Solution

The Template Method design pattern provides a solution:
Define abstract operations (primitives) for the variant parts of a behavior.
Define a template method that
- implements the invariant parts of a behavior and
- calls primitives that subclasses implement.
Describing the Template Method design in more detail is the theme of the following sections.
See Applicability section for all problems Template Method can solve. [BGI]

  • The key idea in this pattern is to control subclassing.
    Subclasses do no longer control how the behavior of a parent class is redefined.
    Instead, a parent class controls how subclasses redefine it.

    This is also referred to as inversion of control. "This refers to how a parent class calls the operations of a subclass and not the other way around." [GoF, p327]
  • Inversion of control is a common feature of frameworks.
    When using a library (reusable classes), we call the code we want to reuse.
    When using a framework (reusable application), we write subclasses and implement the variant code the framework calls.
  • Template methods are a fundamental technique for code reuse
    (1) to implement the common (invariant) parts of a beha­vior once "and leave it up to subclasses to implement the behavior that can vary." [GoF, p326] (2) and from a refactoring point of view, to eliminate code duplication by factoring out invariant behavior among classes and localizing (generalizing) it in a common class.

Background Information

  • The pattern calls abstract operations for variant parts of a behavior primitives because the template method composes primitive operations to get a more complex operation.

Applicability

Design Problems

  • Code Reuse / Redefining Parts of a Behavior
    • How can the invariant parts of a behavior be implemented once
      so that subclasses can implement the variant parts?
    • How can subclasses redefine certain parts of a behavior
      without changing the behavior's structure?
  • Extending Behavior at Specific Points
    • How can subclasses extend a behavior only at specific points (hooks)?
  • Controlling Subclassing
    • How can a class control how it is subclassed?

Refactoring Problems

  • Duplicated Code
    • How can common behavior among classes be factored out
      and localized (generalized) in a common class?
      Form Template Method (205) [JK05]
      "[…] common behavior among subclasses should be factored
      and localized in a common class to avoid code duplication." [GoF, p326]

Structure

Static Class Structure

  • AbstractClass
    • Defines a templateMethod() operation that defines the skeleton (template) of a behavior by implementing the invariant parts of the behavior and calling abstract primitive1() and primitive2() operations to defer implementing the variant parts to SubClass1.
    • Defines abstract primitive operations for the variant parts of a behavior.
  • SubClass1,…
    • Implement the abstract primitive operations.

Implementation

Implementation Issues

  • Different Kinds of Operations
    • "To reuse an abstract class effectively, subclass writers must understand which operations are designed for overriding." [GoF, p328]
    • Primitive operations - abstract operations that must be implemented by subclasses; or concrete operations that provide a default implementation and can be redefined by subclasses if necessary.
      Primitive operations can be declared protected to enable subclassing over package boundaries but keeping clients from calling them directly (see Sample Code).
    • Final operations - concrete operations that can not be overridden by subclasses.
    • Hook operations - concrete operations that do nothing by default and can be redefined by subclasses if necessary.
    • Template methods themselves can be declared final so that they can not be overridden.

Sample Code 1

Basic Java code for implementing the sample UML diagram.

 1  package com.sample.templatemethod.basic;
 2  public abstract class AbstractClass { 
 3      //
 4      protected abstract void primitive1();
 5      protected abstract void primitive2();
 6      //
 7      public final void templateMethod() { 
 8          // ...
 9          primitive1(); 
10          // ...
11          primitive2(); 
12          // ...
13      } 
14  } 

 1  package com.sample.templatemethod.basic;
 2  public class SubClass1 extends AbstractClass { 
 3      //
 4      protected void primitive1() { 
 5          // ...
 6      } 
 7      protected void primitive2() { 
 8          // ...
 9      } 
10  } 

Sample Code 2

Template method with abstract and concrete primitive operations.

 1  package com.sample.templatemethod.steps;
 2  public abstract class AbstractClass { 
 3      // Abstract primitive operation:
 4      // - provides no default implementation
 5      // - must be implemented (overridden).
 6      protected abstract void primitive1();
 7      //
 8      // Concrete primitive operation:
 9      // - provides a default implementation
10      // - can be changed (overridden) optionally.
11      protected void primitive2() { 
12          // variant code ...
13      } 
14      public final void templateMethod() { 
15          // invariant code ...
16          primitive1(); // calling primitive1 (variant code)
17          // invariant code ...
18          primitive2(); // calling primitive2 (variant code)
19          // invariant code ...
20      } 
21  } 

 1  package com.sample.templatemethod.steps;
 2  public class SubClass1 extends AbstractClass { 
 3      //
 4      protected void primitive1() { 
 5          // variant code ...
 6      } 
 7  } 

Not included on this page: Intent, Motivation, Consequences, Related Patterns. See the GoF Design Patterns Reference (PDF) for the complete description.