Template Method Design Pattern
This has nothing to do with Template (C++).
Introduced in CS247 after introducing the Liskov Substitution Principle.
The Template Method Pattern is used when a subclass should be able to modify same parts of a method’s behavior, but not all.
With Template Method Pattern, we provide a structure/recipe/template for what this method will do.
Use Case of Template Method Pattern
Allow subclasses to customize portions (but not all) of this method by performing overrides.
In video game, I have two types of Turtle
s: RedTurtle
+ GreenTurtle
.
There are 2 really important things to notice here:
draw
method is public and non-virtual- Nobody who subclasses
Turtle
can overridedraw
. GreenTurtle
andRedTurtle
can define draw, but it won’t be an override, won’t be called if we useTurtle
s polymorphically
- Nobody who subclasses
drawShell
is private, but we can still override it!- Access specifiers only describe when methods can be called, not how they may be overwritten.
From CS138
This is a (very simple) example of the TemplateMethod design pattern:
- The parent has a high-level recipe that is the same for all children
- … but the recipe has sub-pieces whose details will be different depending on the details of the children
- The parent method is (typically)
public
, while the recipe sub-pieces areprivate
and abstract and declared in the parent - The children figure out how to implement the recipe sub-pieces; the parent specifies the rest.
Example