How to use Template Method pattern
What is Template Method?
Template Method is a Behavioral Design Pattern.
It is used when you need to create multiple variants of an algorithm with large parts of code shared between the variants.
It states as follows — “define an algorithm as a series of operations and let child classes customize these operations as required.”
With Template Method, you break down your algorithm into a series of calling functions and let the variations decide which part of these series of steps be reused or replaced.
Template Method can also help you create “Hooks”, which are optional pieces of steps that have a default implementation in place. The variations can either replace with their own specialties or can leave it as it is for the defaults to work.
How to implement Template Method Design Pattern?
1. Split the algorithm into multiple methods inside an abstract base class. This base class also contains shared code among the variations.
2. All the variants of the algorithms are represented by derived concrete classes that extend this base abstract class. These concrete classes also contain their own implementation of the parts which is specific to them.
3. A Template method inside the base class is the starting point, which calls the sequence of operations involved with the algorithm.
4. A calling client receives an instance of the variation it requires as a type of the abstract base class and call the Template method.
Implementing Template Method with a C# Example
The following code explains how to implement Template Method in C#
Differences between Template Method and Strategy
Template Method is based on Inheritance. Strategy pattern is based on composition — it works on with objects. Template method is Static - binding happens at compile-time. Strategy switches based on client choice during runtime.
Template method runs at class level. Strategy at object level.
Full Article — https://referbruv.com/blog/understanding-template-method-pattern-made-easy/