Design Patterns: TemplateBlog

Software Design Patterns with PlantUML: Template

post-thumb

Introduction

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“:

Design Pattern

You can click on the diagram to open it online in Pladitor.

Diagram Sources

Here are the diagram sources:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
@startuml
class AbstractClass {
templateMethod()
{abstract} primitiveOperation1()
{abstract} primitiveOperation2()
}
class ConcreteClass

ConcreteClass : primitiveOperation1()
ConcreteClass : primitiveOperation2()

AbstractClass <|.. ConcreteClass

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

Open this diagram online with Pladitor.

Share: