Template Method

Behavioral pattern

The template design pattern focuses on code reutilization for implementing steps to solve problems. This is achieved by implementing base classes for defining basic behaviors. Typically, methods are created for each step of the algorithm; some of these will be implemented while others remain abstract until they are executed by the subclasses.

Template Method design pattern structure.
Template Method design pattern structure.

The components included in the Template Method pattern are as follows:

  • Client: It's the component which triggers the execution of the template.
  • AbstractTemplete: It's an abstract class including a series of operations which define the necessary steps for carrying out the execution of the algorithm. This class has a templateMethod method for executing step1, step2 and step3 in order.
  • Implementation: This class represents a concrete template which inherits from AbstractTemplate and implements its methods.
Template Method pattern sequence diagram.
Template Method pattern sequence diagram.
  1. The client creates and gets an instance of the template implementation.
  2. The client executes the templateMethod .
  3. The default implementation of templateMethod executes the step1, step2, step3methods in order.
  4. The template implementation returns a result.

Real-world example

By implementing the Templete Method design pattern, we are going to develop an application for processing payment files. These files are generated by grocery stores or convenience stores where the customers can pay services, such as electricity, water, cable, internet, phone, etcetera. At the end of each day, these stores would generate a plain text file to be sent to the respective companies in order for them to process the payments. With the Template pattern, we will learn how to process any type of file in a clear, simple and generic manner.

Discover how the Template Method pattern can help us solve this problem.
Discover how the Template Method pattern can help us solve this problem.

About this book

Introduction to design patterns

Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:

See book
All rights reserved ©
Reactive programming
LinkedinYoutubeTwitterFacebook

© 2021, Copyright - Oscar Blancarte. All rights reserved.