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.

Design Patterns : Chain of Responsibility

The intend of Chain of Responibility Pattern is to avoid coupling the sender of a request to its reciever by giving more than one object change to handle the request.

Let’s try to mimic the execution of classical Waterfall Model with CoR. Let’s begin by declaring the contract interface.

public interface IWaterfall
    {
        void Execute();
        IWaterfall NextStage { get; set; }
    }

And our sub classes.

internal class Requirements : IWaterfall
{
        public IWaterfall NextStage {get;set;}

        public void Execute()
        {
            Console.WriteLine(nameof(Requirements));

            if (NextStage is IWaterfall)
                NextStage.Execute();
        }
}

internal class Design : IWaterfall
{
        public IWaterfall NextStage { get; set; }

        public void Execute()
        {
            Console.WriteLine(nameof(Design));

            if (NextStage is IWaterfall)
                NextStage.Execute();
        }
}

internal class Implementation : IWaterfall
{
        public IWaterfall NextStage { get; set; }

        public void Execute()
        {
            Console.WriteLine(nameof(Implementation));

            if (NextStage is IWaterfall)
                NextStage.Execute();
        }
}

internal class Verification : IWaterfall
{
        public IWaterfall NextStage { get; set; }

        public void Execute()
        {
            Console.WriteLine(nameof(Verification));

            if (NextStage is IWaterfall)
                NextStage.Execute();
        }
}

internal class Deployment : IWaterfall
{
        public IWaterfall NextStage { get; set; }

        public void Execute()
        {
            Console.WriteLine(nameof(Deployment));

            if (NextStage is IWaterfall)
                NextStage.Execute();
        }
}

internal class Maintenance : IWaterfall
{
        public IWaterfall NextStage { get; set; }

        public void Execute()
        {
            Console.WriteLine(nameof(Maintenance));

            if (NextStage is IWaterfall)
                NextStage.Execute();
        }
}

The final step is link up the chain and get the execution rolling from client.

IWaterfall Handler1 = new Requirements();
IWaterfall Handler2 = new Design();
IWaterfall Handler3 = new Implementation();
IWaterfall Handler4 = new Verification();
IWaterfall Handler5 = new Deployment();
IWaterfall Handler6 = new Maintenance();

Handler1.NextStage = Handler2;
Handler2.NextStage = Handler3;
Handler3.NextStage = Handler4;
Handler4.NextStage = Handler5;
Handler5.NextStage = Handler6;

Handler1.Execute();

As you can see the responsibility is handled by the chain of classes, each executing a single responsibility (following Single Responsibility Principle). Also, the functionality can be extended by further linking up the chain, thereby satisfying the Open-Closed Principle.

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

Design Patterns : Fascade Pattern

Fascade, name being an analogy to an architectural fascade, intends set the tone for the entire functionality by providing a simplified yet effective interface wrapping away the complex, pooly designed collection of APIs.

Wrong Code

Consider following set of Classes.

public class User : IUser
{
        int _uInstance;
        private bool _IsRunning = false;

        public User(int UserID) => _uInstance = UserID;
        public void StartRunning()
        {
            Console.WriteLine($"User {_uInstance} Running");
            _IsRunning = true;
        }
        public void StopRunning(int UserID) => _IsRunning = false;
        
}

public class GPSTracking : IGPSTracking
{
        public void Start() => Console.WriteLine($"GPS started");
        public void Stop() { }
        public void InitiatizeGPSTracker() { }
        public void TroubleShoot() { }
}

public class MusicPlayer : IMusicPlayer
{
        public void Start(string AlbumName,string Song) => Console.WriteLine($"Music Player - Song {Song} , Album {AlbumName}");
        public void Stop() { }
        public void SearchAlbum(string Song) { }
        public bool Loop { get; set; }
        public void Next() { }
        public void Previous() { }
}

 

The Client Code could be

IUser userInstance = new User(1);
userInstance.StartRunning();

IGPSTracking gpsInstance = new GPSTracking();
gpsInstance.Start();

IMusicPlayer mplayerInstance = new MusicPlayer();
mplayerInstance.Start("MyAlbum","MySong");

As you can see, the Client class is invoking 3 APIs separately and the code look a mess.

Fascade In Action

Idea behind Fascade is to provide a simplified interface. Let’s introduce a Fascade Class now.

class FascadeClass
{
        IUser _uInstance;
        IGPSTracking _gInstance;
        IMusicPlayer _mInstance;

        string _Song;
        string _album;

        
        public FascadeClass(IUser uInstance,IGPSTracking gInstance, IMusicPlayer mInstance)
        {
            _uInstance = uInstance;
            _gInstance = gInstance;
            _mInstance = mInstance;

        }

        public void SetSong(string Album, string Song) { _Song = Song; _album = Album; }

        public void StartRunning()
        {
            _uInstance.StartRunning();
            _gInstance.Start();
            _mInstance.Start(_album, _Song);
        }

        public void StopRunning() { }
}

 

The Client Code would be now much cleaner as we have wrapped the complexity of IUser, IGPSTracking and IMusicPlayer within the Fascade Class.

 FascadeClass fInstance = new FascadeClass(new User(1), new GPSTracking(), new MusicPlayer());
fInstance.SetSong("MyAlbum", "MySong");
fInstance.StartRunning();

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