Member-only story
Mastering Design Patterns with Examples — Template Method Pattern
Encapsulating Algorithms
Overview
We’re on an encapsulation roll; we’ve encapsulated object creation, method invocation, complex interfaces, ducks, pizzas…what could be next? We’re going to get down to encapsulating pieces of algorithms so that subclasses can hook themselves right into a computation anytime they want.
In this chapter, we will talk about another behavioral design pattern — The Template Method pattern. It defines the skeleton of an algorithm in a superclass but lets subclasses override specific steps of the algorithm without changing its structure. Here’s a basic idea:
- In the Template Method pattern, we first define an abstract class that contains a method, called the “template method”, which defines an algorithm. This algorithm is made up of a series of steps, represented by other methods in the class.
- Some of these methods are implemented in the abstract class, while others are left abstract, meaning they are not implemented and must be provided by subclasses.
- Subclasses of this abstract class fill in the missing pieces by implementing these abstract methods. The cool part is that, each subclass can provide its own specialized implementation of these methods, but the…