-
Notifications
You must be signed in to change notification settings - Fork 0
Template Method
Roberto Fronteddu edited this page Jan 25, 2023
·
1 revision
The Template Method is a Behavioral Design Pattern. It works by allowing the definition of a method as a series of steps (method calls) and provides a chance for subclasses to define or redefine some of these steps. The pattern works by defining abstract methods which then have to be implemented by concrete subclasses. These methods are like hooks which are then called by the Template Method.
- You need to defer the implementation of parts of your algorithm which can vary or change.
- AbstractClass: Implements the template method using one or more abstract steps. Each step is an abstract method.
- ConcreteClassA/B: Implement the individual steps which are called by the template method.
- Define the template method. Try to break the algorithm into multiple steps where each step will become an abstract method.
- Implement the abstract steps in one or more subclasses
- The Template Method is an example of the inversion of control principle (don't call us, we will call you).
- Too many steps mean too many methods to override, and too few mean that the subclasses end up defining major parts of the algorithm.
- If the template method is final, it cannot be re-defined by subclasses.
- We can use subclasses and inheritance to reimplement only certain steps.
- Factory Method is often called as one of the steps of the Template Method
- All subclasses implement the steps for the same algorithm.
- Client code relies solely on inheritance to get a variation of the same algorithm
- Each subclass represents a separate algorithm
- Client code uses composition to configure the main class with the chosen strategy.
- Tracking code may require looking up multiple classes.
- Unit testing can become very complicated since they may require some specific state
- java.util.AbstractMap and AbstractSet have many non-abstract methods that are good examples of template method.