05 Dec 2023
Intermediate
The Template Method design pattern is a behavioral pattern that defines the skeleton of an algorithm in the base class but lets subclasses override specific steps of the algorithm without changing its structure. In C#, the Template Method pattern typically involves the following main components:
-
Abstract Class (or Interface):
- Defines the skeleton of the algorithm as a series of steps using abstract methods.
- May include concrete methods that are common to all or some subclasses.
- The template method itself orchestrates the steps.
public abstract class AbstractClass { // The template method defines the skeleton of the algorithm public void TemplateMethod() { // Common steps CommonOperation1(); // Steps to be implemented by subclasses PrimitiveOperation1(); PrimitiveOperation2(); // Additional common steps CommonOperation2(); } // Abstract methods to be implemented by subclasses protected abstract void PrimitiveOperation1(); protected abstract void PrimitiveOperation2(); // Concrete methods that can be common to all subclasses protected void CommonOperation1() { Console.WriteLine("AbstractClass: Common Operation 1"); } protected void CommonOperation2() { Console.WriteLine("AbstractClass: Common Operation 2"); } } -
Concrete Class:
- Implements the abstract methods declared in the abstract class.
- Overrides specific steps of the algorithm as needed.
public class ConcreteClass : AbstractClass { protected override void PrimitiveOperation1() { Console.WriteLine("ConcreteClass: Primitive Operation 1"); } protected override void PrimitiveOperation2() { Console.WriteLine("ConcreteClass: Primitive Operation 2"); } } -
Client:
- Uses the template method by creating an instance of the concrete class.
class Client { static void Main() { AbstractClass templateObject = new ConcreteClass(); templateObject.TemplateMethod(); } }
In this example:
AbstractClassis an abstract class that defines the template method (TemplateMethod) and declares abstract methods (PrimitiveOperation1andPrimitiveOperation2) that must be implemented by subclasses.ConcreteClassis a concrete subclass that implements the abstract methods to provide specific implementations for the algorithm's steps.- The
Clientcreates an instance ofConcreteClassand calls itsTemplateMethodto execute the algorithm.
The Template Method pattern is useful when you have an algorithm with common steps across multiple subclasses, but certain steps need to be customized by each subclass. It provides a way to enforce the structure of the algorithm while allowing flexibility in the implementation of specific steps.