Design Patterns with PlantUML: Template Pattern

This post gives a brief overview about the Template Pattern. The post is part of a series about software design patterns and their UML representations with the help of PlantUML.

The article aims at providing a very short description of the general idea of the pattern in the first part. This also involves a descriptive UML diagram. Then, the second part provides the PlantUML code for the diagram so that these posts can also be used as a source of design patterns in PlantUML syntax.

What is the Template Pattern?

According to Wikipedia, the Template Pattern has two main parts, and typically uses object-oriented programming:

The “template method”, generally implemented as a base class (possibly an abstract class), which contains shared code and parts of the overall algorithm which are invariant. The template ensures that the overarching algorithm is always followed. In this class, “variant” portions are given a default implementation, or none at all.

Concrete implementations of the abstract class, which fill in the empty or “variant” parts of the “template” with specific algorithms that vary from implementation to implementation.

At run-time, a concrete class is instantiated. A main method inherited from the base class is called, which then may call other methods defined by both the base class and subclasses. This performs the overall algorithm in the same steps every time, but the details of some steps depend on which subclass was instantiated.

UML Diagram

The following diagram shows the Template Method Pattern in UML notation. It is based on the corresponding chapter in the book “Head First Design Patterns“:

note left of AbstractClass The AbstractClass contains the template method. end note

note left of ConcreteClass There may be many ConcreteClasses, each implementing the full set of operations required by the template method. end note

note right of ConcreteClass The ConcreteClass implements the abstract operations, which are called when the templateMethod() needs them. end note

note right of AbstractClass::templateMethod The template method makes use of the primitiveOperations to implement an algorithm. It is decoupled from the actual implementation of the operations “”primitiveOperation1()”” “”primitiveOperation2()”” end note @enduml

[/plantuml]

PlantUML Sources

PlantUML is a tool allowing users to create UML diagrams from a plain text language. Here are the PlantUML sources for the above software pattern: