Design Pattern

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 Turtles: RedTurtle + GreenTurtle.

class Turtle {
	virtual void drawShell() = 0;
	void drawHead() { 😄; }
	void drawLegs() {🦵🦵🦵🦵; }
	public:
		void draw() {
			drawHead();
			drawShell();
			drawLegs();
		}
}
 
class RedTurtle: public Turtle {
	void drawShell() override { 🔴; }
};
 
class GreenTurtle: public Turtle {
	void drawShell() override { 🟢; }
};

There are 2 really important things to notice here:

  1. draw method is public and non-virtual
    • Nobody who subclasses Turtle can override draw.
    • GreenTurtle and RedTurtle can define draw, but it won’t be an override, won’t be called if we use Turtles polymorphically
  2. 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 are private and abstract and declared in the parent
  • The children figure out how to implement the recipe sub-pieces; the parent specifies the rest.

Example