Event Aggregator

Even though Event Aggregator could be termed as one of the lesser known patterns, the useful of the pattern cannot be ignored. In fact, it makes me wonder why it is lesser known.

Let us recap the observer pattern. One of the problems with observer pattern is that it could grow out of hand when the system has multiple event sources and multiple event subscribers. The Subscribers could themselves be source of some other events.

The Event Aggregator, as Martin Fowler mentions it, is a single source of truth – or rather in this case, single source of events indirection. It gathers events from multiple sources and propagate them to interested parties. The event aggregator is loosely coupled with both Observers and the Subjects, sitting in the middle of observers and publishers as a centralized message broker, allowing a single point of registration of events.

I have been using Caliburn Micro for my WPF applications for a while and it provides a quite useful implementation of Event Aggregator. Following section discusses a simplified version of Caliburn Micro’s implementation of Event Aggregator.

public interface IEventAggregator
{
    void Subscribe(object subscriber);
    void Unsubscribe(object subscriber);
    void PublishMessage(object message);
}

The Event Aggregator has three major methods exposed. One method each for Subscribing and Unsubscribing, and anther additional method for Subjects to publish events. The Subscribe() method could be defined as

private readonly List<WeakReference<Handler>> _handlers = new List<WeakReference<Handler>>();

public void Subscribe(object subscriber)
{
    lock (_handlers)
    {
        if (_handlers.Any(x => x == subscriber))
        {
            return;
        }

        _handlers.Add(new WeakReference<Handler>(new Handler(subscriber)));
    }
}

The Subscribe() method implementation is pretty straightforward. Each time it is invoked it would add the subscriber instance (passed as parameter) to a collection. The collection has been maintained as WeakReference – being a distant cousin of Observer pattern, the EventAggregator also inheritance some of the memory leak issues that is evident in Observer Pattern. The WeakReference allows us to workaround the problem to an extend.

As seen in the code above, the collection is of a type Handler (or rather WeakReference<Handler> to precise).The Handler Type maintains a reference to the subscriber along with a list of Message Types subscriber is interested in and the corresponding Event Handlers. We will look at the Handler definition before discussing further.

private class Handler
{
    private readonly object _subscriber;
    private Dictionary<Type, MethodInfo> _handlers = new Dictionary<Type, MethodInfo>();
    public Handler(object subscriber)
    {
        _subscriber = subscriber;

        var interfaces = _subscriber.GetType()
                                    .GetTypeInfo()
                                    .ImplementedInterfaces
                                    .Where(x => x.GetTypeInfo().IsGenericType && x.GetGenericTypeDefinition() == typeof(IHandleAsync<>));

        foreach (var @interface in interfaces)
        {
            var genericTypeArg = @interface.GetTypeInfo().GenericTypeArguments[0];
            var method = @interface.GetRuntimeMethod("HandleAsync", new[] { genericTypeArg });

            _handlers.Add(genericTypeArg, method);
        }

    }

    public object Subscriber => _subscriber;
    public void Handle(Type messageType, object message)
    {
        if (!_handlers.ContainsKey(messageType))
        {
            throw new Exception($"Message type {message} not registered");
        }

        var method = _handlers[messageType];
        method.Invoke(_subscriber, new[] { message });
    }
}


As you can observe in the code above, the Handler type uses reflection to iterate over the interfaces implemented by the subscriber. In particular, the Handler is interested in the generic interface IHandleAsync<>. Let us look at the interface first.

public interface IHandleAsync<T> where T : EventMessageBase
{
    Task HandleAsync(T message);
}

As seen in the code above, the interface has only a single method. HandleAsync<T>() which accepts a single parameter of Type T. This interface would be implemented by the subscribers who are interested in the publication of messages of type T.

Let us now look at the Unsubscribe method.

public void Unsubscribe(object subscriber)
{
    lock (_handlers)
    {
        WeakReference<Handler> toRemove = null;
        lock (_handlers)
        {

            foreach (var handler in _handlers)
            {
                if (handler.TryGetTarget(out var target))
                {
                    if (target.Subscriber == subscriber)
                        toRemove = handler;
                }
            }

            if(toRemove != null)
            {
                _handlers.Remove(toRemove);
            }
        }
    }
}

Not too much to explain there other than being conscience of thread safety. One another point to note in the Unsubscribe() method is that it removes any instances of Handler that has been reclaimed by the GC.

The last bit of code we need to look at in the implementation of EventAggregator is the PublishMessage() method.

public void PublishMessage(object message)
{
    if (message == null) throw new ArgumentNullException(nameof(message));

    var handlersToNotify = new List<Handler>();
    lock (_handlers)
    {

        foreach(var handler in _handlers)
        {
            if(handler.TryGetTarget(out var target))
            {
                handlersToNotify.Add(target);
            }
        }
    }

    foreach (var handler in handlersToNotify)
    {
        handler.Handle(message.GetType(), message);
    }

}

The core functionality of the PublishMessage() method is to accept a message and iterate over the active Subscribers. It would then inturn Handler instance to check the internal dictionary of the instance has subscribed for the message of type which was accepted as parameter.This is accomplished using the Handler.Handle() method. It would retrieve the event handlers associated and invoke them as seen the code below (implementation of the Handler.Handle() which we had already seen above)

public void Handle(Type messageType, object message)
{
    if (!_handlers.ContainsKey(messageType))
    {
        throw new Exception($"Message type {message} not registered");
    }

    var method = _handlers[messageType];
    method.Invoke(_subscriber, new[] { message });
}

That would complete our EventAggregator. Now it is time to see EventAggregator in action and how the subscriber subscribles themselves.

public class SubscriberAlpha:IHandleAsync<UserSaysHelloMessage>
{
    public SubscriberAlpha(IEventAggregator eventAggregator)
    {
        eventAggregator.Subscribe(this);
    }

    public Task HandleAsync(UserSaysHelloMessage message)
    {
        Console.WriteLine($"Message : {message.Message}");
        return Task.CompletedTask;
    }

}

As seen in the code above, the subscriber has done couple of things here. First, it has implemented the IHandleAsync<> interface with the generic parameter UserSaysHelloMessage.The generic parameter type, in this case UserSaysHelloMessage is the type of the message which this particular subscriber is interested in.

It also uses the instance of IEventAggregator to subscribe to the centerlized EventAggregator. The HandleMessageAsync(UserSaysHelloMessage msg) method would be called by the Event Aggregator when any publisher publishes a message of the same type.

Let us write some client code to see how our little Event Aggregator example works.

var eventAggregator = new EventAggregator();
var subscriber = new SubscriberAlpha(eventAggregator);
var publisher = new PublisherAlpha(eventAggregator);

publisher.PublishMessage("John says hello");

eventAggregator.Unsubscribe(subscriber);

publisher.PublishMessage("John says hello");

Where the PublisherAlpha is defined as

public class PublisherAlpha
{
    private IEventAggregator _aggregator;
    public PublisherAlpha(IEventAggregator eventAggregator)
    {
        _aggregator = eventAggregator;
    }

    public void PublishMessage(string message)
    {
        _aggregator.PublishMessage(new UserSaysHelloMessage(this,message));
    }
}

As expected our output would contain only a single Message.

Message : John says hello

By the time the publisher sends the second message, the subscriber has already unsubscribed from the central message broker. Hence, the second message would not be notified to the subscriber.

While I liked the implementation of Event Aggregator by Caliburn Micro, one part which I would like to tweak around would be have the subscriber the ability to subscribe/unsubscribe individual message types in the runtime. In the next blog post, we will look into another example of Event aggregator implementation, which would address this problem (or rather wish).

If you would like to have a look at the complete code sample shown here, you can access it here in my github.

Gof : Observer Pattern

This has been a long overdue. I had started with this series of byte sized tutorials on various patterns but never went ahead and completed the series. So here am continuing from where I left with the Observer Pattern.

While working with applications, there would times you could have an object which would like to notify other interested object about a change in its state. The interested subscribers could have been implemented in such a way that it sends indefinete amount of request asking the subject if it has changed. But that would not be ideal. Instead, you would want the subject to notify the subscribers every time the state change occurs, thereby avoid the need for the innumerous ‘Is there a state change’ calls.

Imagine how subscribers subscribe to newspaper. As a consumer, one would subscribe a particular newspaper publisher and would be delivered the print each time there is a new one out there. What you do with you print and how you makes use of it is upon the each subscriber, but one thing is common – if you are subscribed to the publisher, you would be notified and given your copy when a new one is out.

This is the princple on which observer pattern works. It ensure an implementation where subscribers and observers can remain loosely coupled while providing the subject the ability to notify the subscribers of state changes.

Let us first have a look at the class diagram and overall summary of the observer pattern.

The core participants of the observer pattern are

  • ISubject
  • ConcreteSubject
  • IObserver
  • ConcreteObservers

The abstract Subject contains methods which can be used by observers to register/unregister themselves. The subject on other hand, maintains a collection of all the observers who have registered themselves with it. It would then use the Update method (part of IObserver) of the observers to notify them of a state change. Let us go ahead and implement the abstract and concrete observers.

// Abstract Subsccriber
public abstract class SubscriberBase
{
    protected readonly INewsPublisher _newsPublisher;
    protected WeakReference<SubscriberBase> _weakReference;
    public SubscriberBase(INewsPublisher publisher)
    {
        _newsPublisher = publisher;
    }
    public abstract void Update(string message);

    public void Subscribe()
    {
        _weakReference= _newsPublisher.Register(this);
    }

    public void Unsubscribe()
    {
        _newsPublisher.Unregister(_weakReference);
    }
}

And now for concrete subscribers.

public class AlphaSubscriber : SubscriberBase
{
    public Guid Id { get; set; }
    public AlphaSubscriber(Guid id, INewsPublisher publisher):base(publisher)
    {
        Id = id;
    }
    public override void Update(string message)
    {
        Console.WriteLine($"{nameof(AlphaSubscriber)}-{Id} has recieved the message {message}");
    }
}

public class BetaSubscriber : SubscriberBase
{
    public int Id { get; set; }
    public BetaSubscriber(int id, INewsPublisher publisher):base(publisher)
    {
        Id = id;
    }
    public override void Update(string message)
    {
        Console.WriteLine($"{nameof(BetaSubscriber)}-{Id} has recieved the message {message}");
    }
}

Notice how the subscribers “Has-A” instance of subject. This allows it too unsubscribe themselves.

Let us now implement the abstract and concrete subjects.

public interface INewsPublisher
{
    WeakReference<SubscriberBase> Register(SubscriberBase subscriber);
    void Unregister(WeakReference<SubscriberBase> subscriber);
    void Publish(string message);
    void AddNews(string news);
}

public class NewsPublisherConcrete : INewsPublisher
{
    public List<WeakReference<SubscriberBase>> _SubscribersCollection = new List<WeakReference<SubscriberBase>>();
    public void AddNews(string news)
    {
        Publish(news);
    }

    public void Publish(string message)
    {
        foreach(var weakReference in _SubscribersCollection)
        {
            if(weakReference.TryGetTarget(out var subscriber))
            {
                subscriber.Update(message);
            }
            else
            {
                _SubscribersCollection.Remove(weakReference);
            }
        }
    }

    public WeakReference<SubscriberBase> Register(SubscriberBase subscriber)
    {
        var weakReference = new WeakReference<SubscriberBase>(subscriber);
        _SubscribersCollection.Add(weakReference);
        return weakReference;
    }

    public void Unregister(WeakReference<SubscriberBase> subscriber)
    {
        _SubscribersCollection.Remove(subscriber);
    }
}

Notice how I have used weak references. This is a protection against memory leaks which may occur in the observer pattern. Every time the client adds a “news” item via the AddNews() method, the Subject would notify the clients iterating over the the references which it has build and calling the Update method of each interested(subscribed) observer. Let us now write client code to complete the example.

var publisher = new NewsPublisherConcrete();

var alphaSubscribers = Enumerable.Range(1,5).Select(x => new AlphaSubscriber(Guid.NewGuid(),publisher)).ToList();
var betaSubscribers = Enumerable.Range(1,3).Select(x => new BetaSubscriber(x,publisher)).ToList();

alphaSubscribers.ForEach(x => x.Subscribe());
betaSubscribers.ForEach(x => x.Subscribe());

Console.WriteLine("Adding message to News");
publisher.AddNews("Hello World");

alphaSubscribers.ForEach(x => x.Unsubscribe());
betaSubscribers.First(x => x.Id == 2).Unsubscribe();
Console.WriteLine("Adding another message to News");
publisher.AddNews("Another Hello World");

That’s all the Observer pattern is all about. In the next part, we will explore the EventAggregator Pattern, a variant of Observer. The complete code samples could be found in my github.

GOF: Composite Pattern

Composite Pattern, in a way, literally takes of from where Decorator Pattern ends. One might be inclined to think of it as a specialized case of Decorator Pattern which composes one or more instances of similiar objects and manipulate them uniformly. This allows the client to work on a single entity or composition of entity uniformily, or in other words, it eliminates the need of programmers to discriminate between leaf and branch, and thereby avoid writing specific logic to handle both scenarios.

The key components of Composite Pattern can be defined as follows

Component
Components defines the interface that specifies the behavior that needs to be uniformly executed by primitive object or composite object.

Leaf
The non-decomposible leaf object, which defines the behavior for the primitive object

Composite
Holds the collection of Child components, and implements the behavior of components that have children.

That would be enough of theory, let’s write some code now. For the sake of example, we will write a little program that would print the size of given File/Directory. Let’s begin by defining the Component interface.

public interface IMetaInfo
{
double GetSize();
}

The next step would be define the behavior of the primitive object, which in this case would be the File.

public class FileObject : IMetaInfo
{
private string _fileName;
public FileObject(string fileName)
{
_fileName = fileName;
}
public double GetSize()
{
Console.WriteLine($"Calculating size of {_fileName}");
return 0;
}
}

As one can understand, the actual behavior is different for File and Directory. The size of Directory needs to be cumiliative size of all the individual Files in it. Let’s define the behavior for Directory Class now.

public class DirectoryObject : IMetaInfo
{
private string _directoryName;
private List<IMetaInfo> _fileCollection;
public DirectoryObject(string directoryName)
{
_directoryName = directoryName;
_fileCollection = new List<IMetaInfo>();
}

public void Add(IMetaInfo file)
{
_fileCollection.Add(file);
}

public void Remove(IMetaInfo file)
{
_fileCollection.Remove(file);
}
public double GetSize()
{
var directorySize = 0d;
foreach (var file in _fileCollection)
{
directorySize += file.GetSize();
}
return directorySize;
}
}

As one could see in the example code, the Directory Structure uses the bahavior of the individual File Structure to calculate the cumiliative Size. Let’s write the code for Client now and see how client can work without having the knowledge of what exactly it is dealing with.

class Client
{
static void Main(string[] args)
{
Console.WriteLine("When using Composite Object");
var directoryInstance = new DirectoryObject("BaseDirectyory");
for(var i = 0; i < 10; i++)
{
directoryInstance.Add(new FileObject($"{i.ToString()}_File"));
}

GetSize(directoryInstance);

Console.WriteLine("When using Component Object");
var fileInstance = new FileObject("Another File Instance");
GetSize(fileInstance);
Console.ReadLine();
}

private static void GetSize(IMetaInfo instance)
{
instance.GetSize();
}
}

The Client.GetSize() method accepts an instance of IMetaInfo as the parameter. It doesn’t really know whether it is actually dealing with a Composite object or a Primitive one.

The Composite pattern is a highly useful pattern when one needs to deal with a irregular structure of objects and composite of objects, enabling the client to deal with them uniformly.

The entire source code shown in this example are available in my GitHub.

Design Pattern : Memento Pattern

Memento Design Pattern allows to capture internal state of an object in an external object and restore it to the desired checkpoint when required, all the while being in compliance with encapsulation.

The Memento Design Pattern comprises of 3 actor classes.

  • Originator : The class which needs to have the ability to store its internal state and restore itself to checkpoint when required.
  • Memento : Contains the internal state of Originator.
  • Caretaker : The shepherd class who is in charge of storing and restoring Originator from Memento.

Let’s go ahead and implement the actor classes

Classic Approach

public class Memento
    {
        public string FName { get; set; }
        public string LName { get; set; }

    }

 public class Caretaker<TSource>
    {

        private IList<Memento> _stateMemory;

        public Caretaker()
        {
            _stateMemory = new List<Memento>();
        }

        public Memento GoBack(int level) =>  _stateMemory.Reverse().Skip(level-1).First();

}

 public class Originator: IOriginator
    {
        public string FName { get; set; }
        public string LName { get; set; }

        public void RestoreState(Memento memento)
        {
            this.FName = memento.FName;
            this.LName = memento.LName;
        }

        public Memento Save()
        {
            return new Memento() {
                LName = this.LName,
                FName = this.FName
            };
        }

    }

The above code showcases the implementation of Memento in its simplest form. You could step up things by making the Memento generic so that it can be reused with other classes as well.

Generic Memento with Serialization.

Instead of defining each properties of the Originator class, we could create a completely generic version by utilizing the powers of serialization.

In the following example implementation of Memento class, I have used ProtoBuf for serializing the class.

public class Memento<TSource>
    {
        private byte[] _state;

        public Memento(TSource data)
        {
            using(var stream = new MemoryStream())
            {
                ProtoBuf.Serializer.Serialize<TSource>(stream, data);
                _state = stream.ToArray();
            }
        }

        public TSource Value
        {
            get
            {
                using(var stream = new MemoryStream(_state))
                {
                    return ProtoBuf.Serializer.Deserialize<TSource>(stream);
                }
            }
        }
    }

The entire source code shown in this example are available in my GitHub.

Design Patterns : Bridge Pattern

The essence of Bridge Pattern lies in the fact that it not just decouples the abstraction from implementation, but in doing so, allows both to evolve independently. Let’s consider the examples of smartphones.

The underlying OS (for sake of example, let’s assume its Android) improving every year. The Android has seen atleast 7 versions in past decade. At the same time, the hardware has also evolved, giving way to new age smartphones. The Abstraction and Implementation has evolved independently here. Let’s mock the scenario using Bridge Pattern.

public interface IAndroid
{
  void Call(string name);
  void Recieve();
  void SendMessage(string name);
  void RecieveMessage();
}
public class KitKat : IAndroid
{
  public void Call(string name) => Console.WriteLine($"Calling {name} using  KitKat");
  public void Recieve() => Console.WriteLine("Recieve using KitKat");
  public void RecieveMessage()=> Console.WriteLine("Recieve Message using  KitKat");
  public void SendMessage(string name) => Console.WriteLine($"Send {name}  Message using KitKat");
}
public class Lollipop : IAndroid
{
  public void Call(string name) => Console.WriteLine($"Calling {name} using  Lollipop");
  public void Recieve() => Console.WriteLine("Recieve using Lollipop");
  public void RecieveMessage() => Console.WriteLine("Recieve Message using  Lollipop");
  public void SendMessage(string name) => Console.WriteLine($"Send {name}  Message using Lollipop");
}
public class Nougat : IAndroid
{
  public void Call(string name) => Console.WriteLine($"Calling {name} using  Nougat");
  public void Recieve() => Console.WriteLine("Recieve using Nougat");
  public void RecieveMessage() => Console.WriteLine("Recieve Message using  Nougat");
  public void SendMessage(string name) => Console.WriteLine($"Send {name}  Message using Nougat");
}

Evolution of Abstraction which Customer/Client sees, the Phone , can be seen in following code.

public class SmartPhone
{
  protected IAndroid _android;
  public SmartPhone(IAndroid android) => _android = android;
  public virtual void Phone(string name) => _android.Call(name);
  public virtual void SendMessage(string name) =>  _android.SendMessage(name);
}
public class NewAgeSmartPhone : SmartPhone
{
  public NewAgeSmartPhone(IAndroid android) : base(android) { }
  public override void Phone(string name)
  {
    Console.WriteLine("New Age Phone Call, Optimization started");
    base._android.Call(name);
  }
  public override void SendMessage(string name)
  {
    Console.WriteLine("New Age Message");
    _android.SendMessage(name);
  }
}

 

Client Code can be shown as following

static void Main(string[] args)
{
  var phone = new SmartPhone(new KitKat());
  var newAgePhone = new NewAgeSmartPhone(new KitKat());
  phone.Phone("Wife");
  newAgePhone.Phone("Wife");
}

 

As seen in the code above, the Bridge Pattern allows the Abstraction and Implementation to vary and evolve independently. Complete Code Sample in this example can found in my GitHub

Design Patterns : Prototype Pattern

Falling under Creational Patterns, Prototype Pattern aims in creating a clone of your object and is used in scenarios when creating a object is considered costly (may be the creation involves a long Database or Web Service Operation). The formal definition of the pattern is as follows.

 

Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.
It is one of the most easiest patterns to implement using .Net Framework.  Let’s define our target class first.
public interface IPerson
{
  string FirstName { get; set; }
  string LastName { get; set; }
  int Age { get; set; }
}
public class Person : IPerson
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public int Age { get; set; }
}

What we need next is an interface that defines our Clone method. One option we have is to define a custom interface which exposes our required method, such as following.

public interface ShallowClone
{
   IPerson Clone(IPerson person);
}

The alternative is to use framework interface ICloneable. For this example, we would be using the framework interface. So let’s go ahead and update the Person Class with implementation of ICloneable.

public class Person : IPerson, ICloneable
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public int Age { get; set; }
  public object Clone() => MemberwiseClone();
}

That’s all we need to do. The MemberwiseClone() method does the trick for us. We will complete the example by writing the Client code.

static void Main(string[] args)
{
  Person personA = new Person { FirstName = "John", LastName= "Burton",  Age = 35 };
  Person personB = personA.Clone() as Person;
  Console.WriteLine($"Person A : {personA.LastName},{personA.FirstName}  - Age : {personA.Age}");
  Console.WriteLine($"Person B : {personB.LastName},{personB.FirstName}  - Age : {personB.Age}");

}

All code samples in this example is available in my GitHub.

Design Patterns : Decorator Pattern

While Inheritance/Sub Classing seems to be most natural way of extending functionality, it might not be always the best option. Especially when you want to avoid subclassing as it might result in too many classes. Consider the following scenario.

Your nearest Dominos has many varieties of Pizzas. On top of it, you could decorate each of those pizzas with extra toppings and choose from a variety of crusts. If we were go with the conventional sub classing approach, we could end up with a lot of sub classes as seen below.
Pizza

For each combination of Pizza and topping, we would need to create a separate sub class. Add to it, options available for crust, and the sub classes could go up higher. This is here Decorator Pattern comes into picture. Decorator Pattern allows us to add functionality/feature to existing classes without having to go through the pain of too many sub classes. Of course, Decorator Pattern too does make use of inheritance, but in a more efficient way.

 

Let’s go ahead and Implement Pizza Classes using Decorator Pattern, beginning with the Contract Interface and choice of base Pizzas.
public interface IPizza
{
  string Description { get; }
  int CalculatePrice();
}

public class MexicanGreenWavePizza : IPizza
{
  public string Description => "Mexican Green Wave Pizza";
  public int CalculatePrice() => 105;
}

public class MargheritaPizza : IPizza
{
  public string Description => "Margherita Pizza";
  public int CalculatePrice() => 100;
}

public class ChickenTikkaPizza : IPizza
{
  public string Description => "Chicken Tikka Pizza";
  public int CalculatePrice() => 115;
}

We will now add our decorators.

class CheeseCrust : IPizza
{
  private IPizza _PizzaInstance;
  public CheeseCrust(IPizza pizza) => _PizzaInstance = pizza;
  public string Description => $"{_PizzaInstance.Description} With Cheese  Crust";
  public int CalculatePrice() => _PizzaInstance.CalculatePrice() + 7;
}

public class ExtraGoldenCorn : IPizza
{
  private IPizza _PizzaInstance;
  public ExtraGoldenCorn(IPizza pizza) => _PizzaInstance = pizza;

  public string Description => $"{_PizzaInstance.Description} with Extra  Golden Corn";
  public int CalculatePrice() => _PizzaInstance.CalculatePrice() + 5;
}

As you might have already noticed, the decorator classes not just inherit from IPizza interface, but it also have an instance of Pizza with it, injected using Dependency Injection.  This allows us to use the decorators with any combination of base classes (and with each other) without having to write too many sub classes as we had observed in the image above. The client can now use any combination of Pizza’s with their decorators.

IPizza vegPizza = new MargheritaPizza();
var vegPizzacheezeCrust = new CheeseCrust(vegPizza); // Added  Decorator

IPizza nonVegPizza = new ChickenTikkaPizza();
var chickenPizzacheezeCrust = new CheeseCrust(nonVegPizza); // Added  Decorator
var chickenPizzacheezeCrustAndExtraGoldenCoren = new  ExtraGoldenCorn(chickenPizzacheezeCrust); // Added Decorator

Console.WriteLine($"{vegPizzacheezeCrust.Description}, Price  :  {vegPizzacheezeCrust.CalculatePrice()}");
Console.WriteLine($"{chickenPizzacheezeCrustAndExtraGoldenCoren.Description},  Price  : {chickenPizzacheezeCrustAndExtraGoldenCoren.CalculatePrice()}");

Output

Margherita Pizza With Cheese Crust, Price  : 107
Chicken Tikka Pizza With Cheese Crust with Extra Golden Corn, Price  : 127<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

The complete reference source code for the example can be found in my Github. To learn more on Design Patterns, refer here.

Design Patterns : State Pattern

State Pattern is share a lot of similarities with Strategy Pattern, but has its own fundamental differences as well. The State pattern allows to change the behavior of a method, depending on the state of an object, in other words it encapsulates the behavior dependent on the state (the What). This is different from the Strategy Pattern which encapsulates the algorithm (the How).

As always, let’s begin by writing a code that showcases the issues faced when we are not using State Pattern.
public enum eState
{
  CardNotInserted,
  NotValidated,
  Validated
}
public class ATMWithoutState
{
  public eState CurrentState { get; set; }


  public void DoOperation()
  {
    switch (CurrentState)
    {
     case eState.CardNotInserted:
        Console.WriteLine("Current: Card Not Inserted, Next: Insert Your Card");
        break;
     case eState.NotValidated:
        Console.WriteLine("Current: Not Valided, Next: Validate your card by entering PIN");
        break;
case eState.Validated:
       Console.WriteLine("Current: Validated, Next: Please enter amount to withdraw");
       break;
    }
  }
}

The switch case exposes the most obvious flaw of this approach, we need to alter the class to add a new state, which is a clear violation of the Open Closed Principle. This is where the State Pattern comes into play, which gives a separate behavior for DoOperation method for different states of Object.

public interface IAtmState
{
  void DoOperation();
}

public class ATMWithState
{
  public IAtmState CurrentState { get; set; }

  public void DoOperation()
  {
    CurrentState.DoOperation();
  }
}

public class CardNotInsertedState : IAtmState
{
  public void DoOperation()
  {
    Console.WriteLine("Current: Card Not Inserted, Next: Insert Your Card");
  }
}

public class NotValidatedState : IAtmState
{
  public void DoOperation()
  {
    Console.WriteLine("Current: Not Valided, Next: Validate your card by entering PIN");
  }
}

public class ValidatedState : IAtmState
{
  public void DoOperation()
  {
    Console.WriteLine("Current: Validated, Next: Please enter amount to withdraw");
  }
}

The complete code described in this post in available in my GitHub.

Patterns,Principles and Programming.

Have been thinking about putting together a collection of Jump Start Tutorials on some core concepts on Programming, finally getting everything together

Design Patterns

Design Principles

Code Smells and Refactoring Techniques