The Template Method Design Pattern is a behavioral design pattern that defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It allows subclasses to provide specific implementations for some parts of an algorithm while keeping the overall structure of the algorithm intact. This pattern is particularly useful when you want to create a common algorithm framework but allow variations in the steps of that algorithm.
Here’s a C# example of the Template Method Design Pattern with a use case for creating a beverage-making template:
Create an Abstract Base Class
Define an abstract base class that contains a template method. The template method outlines the algorithm and includes abstract methods that must be implemented by concrete subclasses.
public abstract class Beverage
{
public void MakeBeverage()
{
BoilWater();
Brew();
PourInCup();
AddCondiments();
}
public abstract void Brew();
public abstract void AddCondiments();
public void BoilWater()
{
Console.WriteLine("Boiling water");
}
public void PourInCup()
{
Console.WriteLine("Pouring into cup");
}
}
Create Concrete Subclasses
Implement concrete subclasses that inherit from the base class. These subclasses provide specific implementations for the Brew
and AddCondiments
methods.
public class Coffee : Beverage
{
public override void Brew()
{
Console.WriteLine("Brewing coffee");
}
public override void AddCondiments()
{
Console.WriteLine("Adding sugar and milk");
}
}
public class Tea : Beverage
{
public override void Brew()
{
Console.WriteLine("Steeping the tea");
}
public override void AddCondiments()
{
Console.WriteLine("Adding lemon");
}
}
Use Case – Making Beverages
Use the Template Method Design Pattern to create and make beverages with the common algorithm but varying steps for different types of beverages.
class Program
{
static void Main(string[] args)
{
Beverage coffee = new Coffee();
Beverage tea = new Tea();
Console.WriteLine("Making coffee:");
coffee.MakeBeverage();
Console.WriteLine("\nMaking tea:");
tea.MakeBeverage();
}
}
In this example, the Template Method Design Pattern defines the common algorithm for making beverages but allows the Coffee
and Tea
subclasses to provide their specific implementations for brewing and adding condiments. When you invoke the MakeBeverage
method, it follows the same overall structure for both types of beverages while customizing the steps based on the beverage type. This pattern is useful for creating reusable algorithm frameworks with variations in specific steps.