Template method is a handy pattern to run common functionality of a base class from the child class. The skeleton of this pattern is there will an abstract
base class with abstract
methods and a common method with implementation which will be used by the implementer classes of the abstract
class. So all objects of the child type can use the common method functionality. Using the following example, we can change the logic of the common methods from the user of those classes.
This will be clear when you see the following example. First of all, we have an abstract
class.
public abstract class TemplateMethod
{
private Action CommonMethodSetToExecute;
public abstract void DisplayOne();
public abstract void DisplayTwo();
public abstract void DisplayThree();
private void DefaultMethodSetToExecute()
{
DisplayOne();
DisplayTwo();
}
public void Execute(Action CommonMethodSetToExecute = null)
{
if (CommonMethodSetToExecute == null)
{
CommonMethodSetToExecute = DefaultMethodSetToExecute;
}
CommonMethodSetToExecute();
}
}
Here is the implementer of this base class:
public class TemplateMethodImp : TemplateMethod
{
public override void DisplayOne()
{
Console.WriteLine("Display method from the implmentor");
}
public override void DisplayTwo()
{
Console.WriteLine("Display two method from the implmentor");
}
public override void DisplayThree()
{
Console.WriteLine("Display three method from the implmentor");
}
}
All the implementers of TemplateMethod
, for example, TemplateMethod1
, TemplateMethod2
, TemplateMethod3
..... TemplateMethodN
have the Execute
method in common, and it can be executed from instances of the TemplateMethod1
, TemplateMethod2
.... TemplateMethodN
classes. But if we have a circumstance for example, where the TemplateMethod2
class needs to execute the Execute
method with a different logic, I introduce an Action
named CommonMethodSetToExecute
in the base class and the Execute
method has an optional CommonMethodSetToExecute
parameter with the default value null
. So when we need to execute the Execute
method, we either pass our new business logic via the CommonMethodSetToExecute
action or just use the default value set for CommonMethodSetToExecute
.
The usage of this Template is as below:
class Program
{
static TemplateMethodImp templateMethodImpObject = new TemplateMethodImp();
static void Main(string[] args)
{
templateMethodImpObject.Execute(templateMethodImpObject.DisplayTwo);
templateMethodImpObject.Execute(ChangedBusinessLogic);
}
static void ChangedBusinessLogic()
{
templateMethodImpObject.DisplayOne();
templateMethodImpObject.DisplayThree();
}
}