Design Patterns : Template Method

The purpose of a Template Method Pattern is to define the skelton of an algorithm, while deferring the exact steps to sub classes. There is plenty of literature on the internet detailing the pattern, so we will skip it and head right to the code.

As always, lets begin by defining the contract interface, in this case, an abstract method.

public abstract class BaseAlgorithm
        public void Execute()
        protected abstract void Step1();
        protected abstract void Step2();
        protected abstract void Step3();

Some of the implementation of Sub classes would be

public class AlgorithmA : BaseAlgorithm
        protected override void Step1() => Console.WriteLine($"{nameof(AlgorithmA)} - {nameof(Step1)}");
        protected override void Step2() => Console.WriteLine($"{nameof(AlgorithmA)} - {nameof(Step2)}");
        protected override void Step3() => Console.WriteLine($"{nameof(AlgorithmA)} - {nameof(Step3)}");

public class AlgorithmB : BaseAlgorithm
        protected override void Step1() => Console.WriteLine($"{nameof(AlgorithmB)} - {nameof(Step1)}");
        protected override void Step2() => Console.WriteLine($"{nameof(AlgorithmB)} - {nameof(Step2)}");
        protected override void Step3() => Console.WriteLine($"{nameof(AlgorithmB)} - {nameof(Step3)}");

public class AlgorithmC : BaseAlgorithm
        protected override void Step1() => Console.WriteLine($"{nameof(AlgorithmC)} - {nameof(Step1)}");
        protected override void Step2() => Console.WriteLine($"{nameof(AlgorithmC)} - {nameof(Step2)}");
        protected override void Step3() => Console.WriteLine($"{nameof(AlgorithmC)} - {nameof(Step3)}");


The Client, on other hand, doesn’t quite need to need know the details of what happens inside the classes.

BaseAlgorithm algo1 = new AlgorithmA();

BaseAlgorithm algo2 = new AlgorithmB();

BaseAlgorithm algo3 = new AlgorithmC();

Code samples can be found here. Complete list of Patterns and Principles could be found here.


One thought on “Design Patterns : Template Method

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s