Design Pattern | Template Method Pattern

What Is the Template Method Pattern?

  • A template is a mold made with certain letters or shapes engraved in it. Looking at a template tells you what kind of characters can be written, but you do not know the exact characters until a concrete writing tool is chosen.
  • The Template Method pattern defines the framework of processing in the superclass and lets subclasses define the concrete details.
  • In GoF design patterns, it is classified as a behavioral design pattern.

Template Method Pattern Example Program

The example program displays a monster’s name, attack power, and defense power.

Class Diagram
Iterator Pattern

The example defines an abstract monster class as the template and concrete monster classes that provide specific attack and defense values. The superclass controls the overall display flow, while subclasses provide the variable parts.

Advantages

The processing skeleton is fixed in one place, and subclasses customize only the details. This reduces duplication and keeps the overall algorithm consistent.