The Template Design Pattern is used to set up the outline or skeleton of an algorithm, leaving the details to specific implementations later. This way, subclasses can override parts of the algorithm without changing its overall structure.
The template pattern is a relatively simple pattern. You can use it when you have some similar classes with only minor differences and it is possible to isolated the differences into one method while the shared similarities are provided by the base class. Using the template pattern the client only has to instantiate the concrete class and call the desired template method.
|
1 2 3 4 5 6 7 8 9 |
class Client { static void Main() { AbstractClass template = new ConcreteClass(); template.TemplateMethod(); Console.ReadKey(); } } |
The abstract class contains a template method which calls an abstract operation which is defined in the base class and implemented in the concrete class.
|
1 2 3 4 5 6 7 8 9 |
abstract class AbstractClass { public void TemplateMethod() { Operation1(); } protected abstract void Operation1(); } |
The concrete class overrides the abstract method of the base class.
|
1 2 3 4 5 6 7 |
class ConcreteClass : AbstractClass { override protected void Operation1() { Console.WriteLine("Operation1 within ConcreteClass"); } } |
Thus, the client calls a template method of the base class which calls a method of a concrete class.
Click here for a simplified
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class Client { static void Main() { MessagePacker template = new XmlMessagePacker(); string message = template.CreateMessage("User324", "Hello, user."); Console.WriteLine(message); Console.ReadKey(); } } abstract class MessagePacker { public string CreateMessage(string to, string message) { return Pack(to, message); } protected abstract string Pack(string to, string message); } class XmlMessagePacker : MessagePacker { override protected string Pack(string to, string message) { return string.Format("{0}{1}", to, message); } } |
This post is part of a series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.
Comments