Saturday, January 13, 2018

Design Pattern : observer pattern

Observer pattern helps us to communicate between parent class and its associated or dependent classes. There are two important concepts in observer pattern ‘Subject’ and ‘Observers’. The subject sends notifications while observers receive notifications if they are registered with the subject. Below figure ‘Subject and observers’ shows how the application (subject) sends notification to all observers (email, event log and SMS). You can map this example to publisher and subscriber model. The publisher is the application and subscribers are email, event log and sms.
Figure: - Subject and Observers

Let’s try to code the same example which we have defined in the previous section. First let’s have a look at the subscribers / notification classes. Figure ‘Subscriber classes’ shows the same in a pictorial format. So we have a common interface for all subscribers i.e. ‘INotification’ which has a ‘notify’ method. This interface ‘INotification’ is implemented by all concrete notification classes. All concrete notification classes define their own notification methodology. For the current scenario we have just displayed a print saying the particular notification is executed.
Figure: - Subscriber classes

As said previously there are two sections in an observer pattern one is the observer/subscriber which we have covered in the previous section and second is the publisher or the subject.

The publisher has a collection of arraylist which will have all subscribers added who are interested in receiving the notifications. Using ‘addNotification’ and ‘removeNotification’ we can add and remove the subscribers from the arraylist. ‘NotifyAll’ method loops through all the subscribers and send the notification.
Figure: - Publisher/Subject classes

Now that we have an idea about the publisher and subscriber classes lets code the client and see observer in action. Below is a code for observer client snippet. So first we create the object of the notifier which has collection of subscriber objects. We add all the subscribers who are needed to be notified in the collection.
Now if the customer code length is above 10 characters then tell notify all the subscribers about the same.
Figure: - Observer client code

Design Pattern : memento pattern

Memento pattern is the way to capture objects internal state with out violating encapsulation. Memento pattern helps us to store a snapshot which can be reverted at any moment of time by the object. Let’s understand what it means in practical sense. Consider figure ‘Memento practical example’, it shows a customer screen. Let’s say if the user starts editing a customer record and he makes some changes. Later he feels that he has done something wrong and he wants to revert back to the original data. This is where memento comes in to play. It will help us store a copy of data and in case the user presses cancel the object restores to its original state.
Figure: - Memento practical example

Let’s try to complete the same example in C# for the customer UI which we had just gone through. Below is the customer class ‘clsCustomer’ which has the aggregated memento class ‘clsCustomerMemento’ which will hold the snapshot of the data. The memento class ‘clsCustomerMemento’ is the exact replica ( excluding methods ) of the customer class ‘clsCustomer’. When the customer class ‘clsCustomer’ gets initialized the memento class also gets initialized. When the customer class data is changed the memento class snapshot is not changed. The ‘Revert’ method sets back the memento data to the main class.
Figure: - Customer class for memento
The client code is pretty simple. We create the customer class. In case we have issues we click the cancel button which in turn calls the ‘revert’ method and reverts the changed data back to the memento snapshot data. Figure ‘Memento client code’ shows the same in a pictorial format.
Figure: - Memento client code

Design Pattern : mediator pattern

Many a times in projects communication between components are complex. Due to this the logic between the components becomes very complex. Mediator pattern helps the objects to communicate in a disassociated manner, which leads to minimizing complexity.
Figure: - Mediator sample example

Let’s consider the figure ‘Mediator sample example’ which depicts a true scenario of the need of mediator pattern. It’s a very user-friendly user interface. It has three typical scenarios.
Scenario 1:- When a user writes in the text box it should enable the add and the clear button. In case there is nothing in the text box it should disable the add and the clear button.
Figure: - Scenario 1

Scenario 2:- When the user clicks on the add button the data should get entered in the list box. Once the data is entered in the list box it should clear the text box and disable the add and clear button.
Figure: - Scenario 2

Scenario 3:- If the user click the clear button it should clear the name text box and disable the add and clear button.
Figure: - Scenario 3

Now looking at the above scenarios for the UI we can conclude how complex the interaction will be in between these UI’s. Below figure ‘Complex interactions between components’ depicts the logical complexity.
Figure: - Complex interactions between components

Ok now let me give you a nice picture as shown below ‘Simplifying using mediator’. Rather than components communicating directly with each other if they communicate to centralized component like mediator and then mediator takes care of sending those messages to other components, logic will be neat and clean.
Figure: - Simplifying using mediator
Now let’s look at how the code will look. We will be using C# but you can easily replicate the thought to JAVA or any other language of your choice. Below figure ‘Mediator class’ shows the complete code overview of what the mediator class will look like.

The first thing the mediator class does is takes the references of the classes which have the complex communication. So here we have exposed three overloaded methods by name ‘Register’. ‘Register’ method takes the text box object and the button objects. The interaction scenarios are centralized in ‘ClickAddButton’,’TextChange’ and ‘ClickClearButton’ methods. These methods will take care of the enable and disable of UI components according to scenarios.
Figure: - Mediator class

The client logic is pretty neat and cool now. In the constructor we first register all the components with complex interactions with the mediator. Now for every scenario we just call the mediator methods. In short when there is a text change we can the ‘TextChange’ method of the mediator, when the user clicks add we call the ‘ClickAddButton’ and for clear click we call the ‘ClickClearButton’.
Figure: - Mediator client logic

Design Pattern : iterator pattern

Iterator pattern allows sequential access of elements with out exposing the inside code. Let’s understand what it means. Let’s say you have a collection of records which you want to browse sequentially and also maintain the current place which recordset is browsed, then the answer is iterator pattern. It’s the most common and unknowingly used pattern. Whenever you use a ‘foreach’ (It allows us to loop through a collection sequentially) loop you are already using iterator pattern to some extent.

Figure: - Iterator business logic

In figure ‘Iterator business logic’ we have the ‘clsIterator’ class which has collection of customer classes. So we have defined an array list inside the ‘clsIterator’ class and a ‘FillObjects’ method which loads the array list with data. The customer collection array list is private and customer data can be looked up by using the index of the array list. So we have public function like ‘getByIndex’ ( which can look up using a particular index) , ‘Prev’ ( Gets the previous customer in the collection , ‘Next’ (Gets the next customer in the collection), ‘getFirst’ ( Gets the first customer in the collection ) and ‘getLast’ ( Gets the last customer in the collection).

So the client is exposed only these functions. These functions take care of accessing the collection sequentially and also it remembers which index is accessed.

Below figures ‘Client Iterator Logic’ shows how the ‘ObjIterator’ object which is created from class ‘clsIterator’ is used to display next, previous, last, first and customer by index.
Figure: - Client Iterator logic

Design Pattern : Interpreter pattern

Interpreter pattern allows us to interpret grammar in to code solutions. Ok, what does that mean?. Grammars are mapped to classes to arrive to a solution. For instance 7 – 2 can be mapped to ‘clsMinus’ class. In one line interpreter pattern gives us the solution of how to write an interpreter which can read a grammar and execute the same in the code. For instance below is a simple example where we can give the date format grammar and the interpreter will convert the same in to code solutions and give the desired output.
Figure: - Date Grammar

Let’s make an interpreter for date formats as shown in figure ‘Date Grammar’. Before we start lets understand the different components of interpreter pattern and then we will map the same to make the date grammar. Context contains the data and the logic part contains the logic which will convert the context to readable format.
Figure: - Context and Logic

Let’s understand what is the grammar in the date format is. To define any grammar we should first break grammar in small logical components. Figure ‘Grammar mapped to classes’ show how different components are identified and then mapped to classes which will have the logic to implement only that portion of the grammar. So we have broken the date format in to four components Month, Day, Year and the separator. For all these four components we will define separate classes which will contain the logic as shown in figure ‘Grammar mapped to classes’. So we will be creating different classes for the various components of the date format.
Figure: - Grammar mapped to classes

As said there are two classes one is the expression classes which contain logic and the other is the context class which contain data as shown in figure ‘Expression and Context classes’. We have defined all the expression parsing in different classes, all these classes inherit from common interface ‘ClsAbstractExpression’ with a method ‘Evaluate’. The ‘Evaluate’ method takes a context class which has the data; this method parses data according to the expression logic. For instance ‘ClsYearExpression’ replaces the ‘YYYY’ with the year value,’’ClsMonthExpression’ replaces the ‘MM’ with month and so on.
Figure :- Class diagram for interpreter
Figure: - Expression and Context classes

Now that we have separate expression parsing logic in different classes, let’s look at how the client will use the iterator logic. The client first passes the date grammar format to the context class. Depending on the date format we now start adding the expressions in a collection. So if we find a ‘DD” we add the ‘ClsDayExpression’, if we find ‘MM’ we add ‘ClsMonthExpression’ and so on. Finally we just loop and call the ‘Evaluate’ method. Once all the evaluate methods are called we display the output.
Figure: - Client Interpreter logic

Design Pattern : Prototype

The prototype design pattern is a design pattern that is used to instantiate a class by copying, or cloning, the properties of an existing object. The new object is an exact copy of the prototype but permits modification without altering the original.
This is another Gang of Four creational pattern. As programmer I’m absolutely sure that you found yourself create objects using new keyword many times and in some cases, when objects has a lot of properties which must be filled it was so boring and quantity of time you spent on this single task was enormous. I thing you agree when I say that today’s programming is all about the costs and saving of resources (especially time) is a big issue. Sometimes you can find another way how to instantiate a new object using existing objects. This type of object creation is called cloning. This practise is very useful when the construction of a new object using new keyword is inefficient.
When original object is cloned, the new object is a shallow (or sometimes called deep) copy, This copy duplicates all of the properties and fields of original object. If a property is reference type, the reference is copied too.

Structural code example

 
The UML diagram below describes an implementation of the prototype design pattern. This diagram consits of two type of classes:
  • Prototype: represents an abstract base class from the objects that can be cloned. This class contains single virtual method Clone() that returns prototype object. .NET framework includes interface named ICloneable which creates a new instance of a class with the same value as an existing instance.
  • ConcretePrototype: this class inherits from Prototype base class and includes additional functionality. In this class is also overriden Clone() method.
static class Program
{
    static void Main()
    {
        ConcretePrototype prototype = new ConcretePrototype("1");
        ConcretePrototype clone = (ConcretePrototype)prototype.Clone();
        Console.WriteLine("Cloned: {0}", clone.Id);
    }
}

abstract class Prototype
{
    private readonly string _id;

    protected Prototype(string id)
    {
        _id = id;
    }

    public string Id
    {
        get { return _id; }
    }

    public abstract Prototype Clone();
}

class ConcretePrototype : Prototype
{
    public ConcretePrototype(string id)
        : base(id)
    {
    }
    public override Prototype Clone()
    {
        return (Prototype)MemberwiseClone();
    }
}

Real world example

In this example I have created two concrete prototype classes: Commander and Infantry. Both of this classes inherites from StormTrooper class. StormTrooper class has two public methods: FirePower and Armor and one public method Clone which returns a shallow copy of object.
class Program
{
    static void Main()
    {
        var stormCommander = new Commander();
        var infantry = new Infantry();


        var stormCommander2 = stormCommander.Clone() as Commander;
        var infantry2 = infantry.Clone() as Infantry;


        if (stormCommander2 != null)
            Console.WriteLine("Firepower: {0}, Armor: {1}",stormCommander2.FirePower,stormCommander2.Armor);

        if (infantry2 != null)
            Console.WriteLine("Firepower: {0}, Armor: {1}", infantry2.FirePower, infantry2.Armor);
    }
}

public abstract class StormTrooper:ICloneable
{
    public int FirePower { get; set; }
    public int Armor { get; set; }

    public object Clone()
    {
        return MemberwiseClone();
    }
}

public class Commander:StormTrooper
{
    public Commander()
    {
        Armor = 15;
        FirePower = 20;
    }
}

public class Infantry : StormTrooper
{
    public Infantry()
    {
        FirePower = 10;
        Armor = 9;
    }
}

Design Pattern : Factory method

The factory method pattern is a design pattern that allows for the creation of objects without specifying the type of object that is to be created in code. A factory class contains a method that allows determination of the created type at run-time.
This is a third of Gang of Four patterns. It also belongs to the creational patterns group. This pattern is also known as Virtual Constructor pattern. The factory method pattern defines an interface for creating an object and leaves the choice of type to the subclasses. Factory method design pattern makes a design more customizable and only a little complicated. Other design pattern require new classes, whereas factory method only requires a new operation.

Structural code example

 
The UML diagram below describes an implementation of the factory method design pattern. This diagram consists of four classes:
  • FactoryBase: this is an abstract class for the concrete factory classes which will return new objects. In some cases it could be a simple interface containing the signature for the factory method. This class contains FactoryMethod which returns a ProductBase object.
  • ConcreteFactory: represents concrete implementation of factory. Usually this class overrides the generating FactoryMethod and returns a ConcreteProduct object.
  • ProductBase: this is a base class for all products created by concrete factories. In some cases it could be a simple interface.
  • ConcreteProduct: this is a concrete implementation of ProducBase. Concrete product classes can include specific functionality. This objects are created by factory methods.
static class Program
{
    static void Main()
    {
        FactoryBase factory = new ConcreteFactory();
        ProductBase product = factory.FactoryMethod(1);
        product.ShowInfo();
        product = factory.FactoryMethod(2);
        product.ShowInfo();
    }
}

public abstract class FactoryBase
{
    public abstract ProductBase FactoryMethod(int type);
}

public class ConcreteFactory : FactoryBase
{
    public override ProductBase FactoryMethod(int type)
    {
        switch (type)
        {
            case 1:
                return new ConcreteProduct1();
            case 2:
                return new ConcreteProduct2();
            default:
                throw new ArgumentException("Invalid type.", "type");
        }
    }
}


public abstract class ProductBase
{
    public abstract void ShowInfo();
}

public class ConcreteProduct1 : ProductBase {
    public override void ShowInfo()
    {
        Console.WriteLine("Product1");
    }
}

public class ConcreteProduct2 : ProductBase {
    public override void ShowInfo()
    {
        Console.WriteLine("Product2");
    }
}

Real world example

In this example I have chosen the vehicle manufacturing example again. We have one interface IVehicleFactory with one method CreateVehicle which returns Vehicle object. Another two classes FordExplorerFactory and LincolnAviatorFactory are concrete implement this interface. In case of FordExplorerFactory, method CreateVehicle returns FordExplorer object which derives from abstract Vehicle class and overrides ShowInfo method. This method only displays information about vehicle. FordExploredClass has one default constructor which fills properties of this object.
In case of LincolnAviatorFactory is a situation a slightly bit different. Method CreateVehicle returns LincolnAviator object, but this object has one constructor with parameters which values are used to fill object’s properties.
This example demonstrates how to use different factories for creating a different types of objects.
class Program
{
    static void Main(string[] args)
    {
        IVehicleFactory factory = GetFactory("FactoryMethodPattern.ConcreteFactories.LincolnAviatorFactory");

        var lincolnAviator = factory.CreateVehicle();

        lincolnAviator.ShowInfo();

        factory = GetFactory("FactoryMethodPattern.ConcreteFactories.FordExplorerFactory");

        var fordExplorer = factory.CreateVehicle();

        fordExplorer.ShowInfo();
    }

    static IVehicleFactory GetFactory(string factoryName)
    {
        return Assembly.GetExecutingAssembly().CreateInstance(factoryName) as IVehicleFactory;
    }
}

public interface IVehicleFactory
{
    Vehicle CreateVehicle();
}

public abstract class Vehicle
{
    public string Model { get; set; }
    public string Engine { get; set; }
    public string Transmission { get; set; }
    public string Body { get; set; }
    public int Doors { get; set; }
    public List<string> Accessories = new List<string>();

    public abstract void ShowInfo();
}

public class FordExplorerFactory:IVehicleFactory
{
    public Vehicle CreateVehicle()
    {
        return new FordExplorer();
    }
}

public class LincolnAviatorFactory:IVehicleFactory
{
    public Vehicle CreateVehicle()
    {
        return new LincolnAviator("Lincoln Aviator",
            "4.6 L DOHC Modular V8",
            "5-speed automatic",
            "SUV",4);
    }
}

public class FordExplorer:Vehicle
{
    public FordExplorer()
    {
        Model = "Ford Explorer";
        Engine = "4.0 L Cologne V6";
        Transmission = "5-speed M50D-R1 manual";
        Body = "SUV";
        Doors = 5;
        Accessories.Add("Car Cover");
        Accessories.Add("Sun Shade");
    }

    public override void ShowInfo()
    {
        Console.WriteLine("Model: {0}", Model);
        Console.WriteLine("Engine: {0}", Engine);
        Console.WriteLine("Body: {0}", Body);
        Console.WriteLine("Doors: {0}", Doors);
        Console.WriteLine("Transmission: {0}", Transmission);
        Console.WriteLine("Accessories:");
        foreach (var accessory in Accessories)
        {
            Console.WriteLine("\t{0}", accessory);
        }
    }
}

public class LincolnAviator:Vehicle
{
    public LincolnAviator(string model, string engine, string transmission, string body, int doors)
    {
        Model = model;
        Engine = engine;
        Transmission = transmission;
        Body = body;
        Doors = doors;
        Accessories.Add("Leather Look Seat Covers");
        Accessories.Add("Chequered Plate Racing Floor");
        Accessories.Add("4x 200 Watt Coaxial Speekers");
        Accessories.Add("500 Watt Bass Subwoofer");
    }

    public override void ShowInfo()
    {
        Console.WriteLine("Model: {0}", Model);
        Console.WriteLine("Engine: {0}", Engine);
        Console.WriteLine("Body: {0}", Body);
        Console.WriteLine("Doors: {0}", Doors);
        Console.WriteLine("Transmission: {0}", Transmission);
        Console.WriteLine("Accessories:");
        foreach (var accessory in Accessories)
        {
            Console.WriteLine("\t{0}", accessory);
        }
    }
}

Design Pattern : Builder

The builder pattern is a design pattern that allows for the step-by-step creation of complex objects using the correct sequence of actions. The construction is controlled by a director object that only needs to know the type of object it is to create.
Builder pattern is another Gang of Four design pattern which belong to the creational design patterns family. The intent of the builder pattern is to separate the construction of a complex object from its representation. This pattern is used when complex object that need to be created is constructed by constituent parts that must by created in the same order or by using a specific algorithm.

Structural code example

The UML diagram below describes an implementation of the builder design pattern. This diagram consists of four classes:
  • Product: represents the complex object that is being built.
  • Builder: this is base class (or interface) for all builders and defines a steps that must be taken in order to correctly create an complex object (product). Generally each step is an abstract method that is overriden by concrete implementation.
  • ConcreteBuilder: provides implementation for builder. Builder is an object able to create other complex objects (products).
  • Director: represents class that controls algorithm used for creation of complex object. 
static class Program
{
    static void Main()
    {
        Builder b1 = new ConcreteBuilder1();

        Director.Construct(b1);
        var p1 = b1.GetResult();
        p1.Show();
    }
}

static class Director
{
    public static void Construct(Builder builder)
    {
        builder.BuildPartA();
        builder.BuildPartB();
    }
}

abstract class Builder
{
    public abstract void BuildPartA();
    public abstract void BuildPartB();
    public abstract Product GetResult();
}

class ConcreteBuilder1 : Builder
{
    private readonly Product _product = new Product();

    public override void BuildPartA()
    {
        _product.Add("Part A");
    }

    public override void BuildPartB()
    {
        _product.Add("Part B");
    }

    public override Product GetResult()
    {
        return _product;
    }
}

class Product
{
    private readonly List<string> _parts = new List<string>();

    public void Add(string part)
    {
        _parts.Add(part);
    }

    public void Show()
    {
        Console.WriteLine("Parts:");
        foreach (string part in _parts)
            Console.WriteLine("\t"+part);
    }
}

Real world example

Now let’s take a look at real world example. As a real world example I choose vehicle manufacturing. In this example I have created abstract class VehicleBuilder (Builder) which is a base class for all concrete builder classes (FordExplorerBuilder and LincolnAviatorBuilder). This class has method CreateVehicle which instantiates protected _vehicle field of type Vehicle (Product). Other methods are abstract and must be overriden by concrete builder implementation. This methods set properties of _vehicle. The last class VehicleCreator plays role as Director. It has constructor with one VehicleBuilder parameter and method CreateVehicle which controls steps for creation of object and filling it’s properties. Method GetVehiclereturns fully constructed Vehicle object.
class Program
{
    static void Main()
    {
        var vehicleCreator = new VehicleCreator(new FordExplorerBuilder());
        vehicleCreator.CreateVehicle();
        var vehicle = vehicleCreator.GetVehicle();
        vehicle.ShowInfo();

        Console.WriteLine("---------------------------------------------");

        vehicleCreator = new VehicleCreator(new LincolnAviatorBuilder());
        vehicleCreator.CreateVehicle();
        vehicle = vehicleCreator.GetVehicle();
        vehicle.ShowInfo();

    }
}

public abstract class VehicleBuilder
{
    protected Vehicle _vehicle;

    public Vehicle GetVehicle()
    {
        return _vehicle;
    }

    public void CreateVehicle()
    {
        _vehicle = new Vehicle();
    }

    public abstract void SetModel();
    public abstract void SetEngine();
    public abstract void SetTransmission();
    public abstract void SetBody();
    public abstract void SetDoors();
    public abstract void SetAccessories();
}
...
class FordExplorerBuilder : VehicleBuilder
{
    public override void SetModel()
    {
        _vehicle.Model = "Ford Explorer";
    }

    public override void SetEngine()
    {
        _vehicle.Engine = "4.0 L Cologne V6";
    }

    public override void SetTransmission()
    {
        _vehicle.Transmission = "5-speed M5OD-R1 manual";
    }

    public override void SetBody()
    {
        _vehicle.Body = "SUV";
    }

    public override void SetDoors()
    {
        _vehicle.Doors = 5;
    }

    public override void SetAccessories()
    {
        _vehicle.Accessories.Add("Car Cover");
        _vehicle.Accessories.Add("Sun Shade");
    }
}
...
class LincolnAviatorBuilder : VehicleBuilder
{
    public override void SetModel()
    {
        _vehicle.Model = "Lincoln Aviator";
    }

    public override void SetEngine()
    {
        _vehicle.Engine = "4.6 L DOHC Modular V8";
    }

    public override void SetTransmission()
    {
        _vehicle.Transmission = "5-speed automatic";
    }

    public override void SetBody()
    {
        _vehicle.Body = "SUV";
    }

    public override void SetDoors()
    {
        _vehicle.Doors = 4;
    }

    public override void SetAccessories()
    {
        _vehicle.Accessories.Add("Leather Look Seat Covers");
        _vehicle.Accessories.Add("Chequered Plate Racing Floor");
        _vehicle.Accessories.Add("4x 200 Watt Coaxial Speekers");
        _vehicle.Accessories.Add("500 Watt Bass Subwoofer");
    }
}
...
public class VehicleCreator
{
    private readonly VehicleBuilder _builder;

    public VehicleCreator(VehicleBuilder builder)
    {
        _builder = builder;
    }

    public void CreateVehicle()
    {
        _builder.CreateVehicle();
        _builder.SetModel();
        _builder.SetEngine();
        _builder.SetBody();
        _builder.SetDoors();
        _builder.SetTransmission();
        _builder.SetAccessories();
    }

    public Vehicle GetVehicle()
    {
        return _builder.GetVehicle();
    }
}
...
public class Vehicle
{
    public string Model { get; set; }
    public string Engine { get; set; }
    public string Transmission { get; set; }
    public string Body { get; set; }
    public int Doors { get; set; }
    public List<string> Accessories { get; set; }

    public Vehicle()
    {
        Accessories = new List<string>();
    }

    public void ShowInfo()
    {
        Console.WriteLine("Model: {0}",Model);
        Console.WriteLine("Engine: {0}", Engine);
        Console.WriteLine("Body: {0}", Body);
        Console.WriteLine("Doors: {0}", Doors);
        Console.WriteLine("Transmission: {0}", Transmission);
        Console.WriteLine("Accessories:");
        foreach (var accessory in Accessories)
        {
            Console.WriteLine("\t{0}",accessory);
        }
    }
}