In Template Method design pattern, we define our specific algorithm in the base class. A algorithm can compose of several methods. At designing the base class, we don’t know the implementation of some methods and we mark these methods as abstract so that subclasses can implement these methods. A method in the base class which use abstract methods are called Template Method.
In this pattern, a subclass cannot modify the base class algorithm. Subclasses can only implement some base class methods which are not implemented in base class.
Structure
Participants
AbstractClass: Defines primitive operations and a Template Method which use these primitive methods internally.
ConcreteClass: A subclass which Implements these primitive operations.
Example of Template Method Pattern
In the above diagram, we have a BaseFile class which defines one abstract method FormatFile. JsonFile, XMLFile, and TxtFile are subclasses of BaseFile and these classes implement FormatFile method. LoadFile, SaveFile, DoWork and Run methods are already implemented in the base class.
A Run() method in the base class defines an algorithm. In the algorithm, we call LoadFile(), FormatFile(), DoWork() and then SaveFile() methods in the order. As Run() method defines an algorithm, we call Run() method a Template Method.
Below is the implementation of above diagram in C#.
class Program
{
static void Main(string[] args)
{
BaseFile jsonFile = new JsonFile();
jsonFile.Run();
Console.WriteLine("");
BaseFile xmlFile = new XMLFile();
xmlFile.Run();
Console.WriteLine("");
BaseFile txtFile = new TxtFile();
txtFile.Run();
Console.WriteLine("");
}
}
public abstract class BaseFile
{
public void LoadFile()
{
Console.WriteLine("Loading file");
}
public abstract void FormatFile(); //abstract method
public void SaveFile()
{
Console.WriteLine("Saving file");
}
public void DoWork()
{
Console.WriteLine("Working on file");
}
public void Run()
{
LoadFile();
FormatFile();
DoWork();
SaveFile();
}
}
public class JsonFile : BaseFile
{
public override void FormatFile()
{
Console.WriteLine("Formatting Json File");
}
}
public class XMLFile : BaseFile
{
public override void FormatFile()
{
Console.WriteLine("Formatting XML File");
}
}
public class TxtFile : BaseFile
{
public override void FormatFile()
{
Console.WriteLine("Formatting Txt File");
}
}