| Type | Behavioral |
| Purpose | Define the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. |
Description
The Template Method pattern defines the overall structure of an algorithm in an abstract class while allowing subclasses to provide their own implementations for particular steps. This allows the algorithm's structure to remain fixed while specific parts of its behaviour can vary between subclasses. In this way, the pattern supports extension without altering the fundamental flow of the algorithm.
Template Method is primarily concerned with defining an algorithm's skeleton while allowing selected steps to vary.
Overview
| AbstractClass | This class defines a template method that consists of a skeleton of some algorithm composed of method calls. This algorithm represents an operation or a series of steps required for some process. Some of these steps are primitive and are deferred to subclasses. |
| ConcreteClass | Subclasses of the AbstractClass that implement the operations deferred by the template method. |
Implementation
// Abstract Class
public abstract class Messenger
{
public void Execute()
{
var message = SelectMessage();
message = Format(message);
Display(message);
}
protected abstract string SelectMessage();
protected abstract string Format(string message);
protected abstract void Display(string message);
}
// Concrete Classes
public class ConsoleMessenger : Messenger
{
protected override string SelectMessage()
=> "Hello World!";
protected override string Format(string message)
=> message.ToUpperInvariant();
protected override void Display(string message)
=> Console.WriteLine(message);
}
public class HtmlMessenger : Messenger
{
protected override string SelectMessage()
=> "Hello World!";
protected override string Format(string message)
=> $"<h1>{message}</h1>";
protected override void Display(string message)
=> Console.WriteLine(message);
}
// Demonstration
public static class TemplateMethodDemo
{
public static void Execute()
{
var consoleMessenger = new ConsoleMessenger();
consoleMessenger.Execute();
var htmlMessenger = new HtmlMessenger();
htmlMessenger.Execute();
}
}
// outputs:
// HELLO WORLD!
// <h1>Hello World!</h1>
Summary
For more information, please see here.