Template Method

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:

Template Method Design Pattern C#

The classes, interfaces, and objects in the above UML class diagram are as follows:

  1. AbstractClass

    This is an abstract class that contains template method and abstract operations for each of the steps that may be implemented by subclasses.

  2. 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:

Real Life Example of Template Method Design Pattern C#

When to use it?

  1. An abstract view of an algorithm is required, but implementation varies according to the subclasses.

  2. Common behaviors of subclasses can be used to make to a common class.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +