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
Template MethodBehavioral 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.
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.
- The client creates and gets an instance of the template implementation.
- The client executes the templateMethod .
- The default implementation of templateMethod executes the step1, step2, step3methods in order.
- The template implementation returns a result.
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.