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()
        {
            Step1();
            Step2();
            Step3();
        }
        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();
algo1.Execute();

BaseAlgorithm algo2 = new AlgorithmB();
algo2.Execute();

BaseAlgorithm algo3 = new AlgorithmC();
algo3.Execute();

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

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s