13
SepTemplate Method Design Pattern
Template Method Design Pattern falls under Behavioral Pattern of Gang of Four (GOF) Design Patterns in .Net. The command pattern is commonly used in the menu systems of many applications such as Editor, IDE, etc. In this article, I would like to share what is template method pattern and how is it work?
What is Template Method Design pattern?
Template method pattern is used to define the basic steps of an algorithm and allow the implementation of the individual steps to be changed. This pattern looks similar to the strategy design pattern. The main difference is the ability to change the parts of an algorithm rather than replacing an entire algorithm.
In the Template pattern, an abstract class defined the template method and this method includes the steps which are implemented by the subclasses.
Template Method Design Pattern - UML Diagram & Implementation
The UML class diagram for the implementation of the Template Method Design Pattern is given below:
The classes, interfaces, and objects in the above UML class diagram are as follows:
AbstractClass
This is an abstract class that contains template method and abstract operations for each of the steps that may be implemented by subclasses.
ConcreteClassA/B
These are subclasses which inherit the abstract class and override the abstract class operations.
C# - Implementation Code
public abstract class AbstractClass { public void TemplateMethod() { Step1(); Step2(); Step3(); } public abstract void Step1(); public abstract void Step2(); public abstract void Step3(); } public class ConcreteClassA : AbstractClass { public override void Step1() { Console.WriteLine("Concrete Class A, Step 1"); } public override void Step2() { Console.WriteLine("Concrete Class A, Step 2"); } public override void Step3() { Console.WriteLine("Concrete Class A, Step 3"); } } public class ConcreteClassB : AbstractClass { public override void Step1() { Console.WriteLine("Concrete Class B, Step 1"); } public override void Step2() { Console.WriteLine("Concrete Class B, Step 2"); } public override void Step3() { Console.WriteLine("Concrete Class B, Step 3"); } }
Real Life Example:
When to use it?
An abstract view of an algorithm is required, but implementation varies according to the subclasses.
Common behaviors of subclasses can be used to make to a common class.
What do you think?
I hope you will enjoy the Template Method Design Pattern while designing your software. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.