A day with .Net

My day to day experince in .net

Archive for the ‘Design Patterns’ Category

Strategy Pattern

Posted by vivekcek on May 5, 2015

This pattern enables an algorithm’s behavior to be selected at run-time.

The strategy pattern:

defines a family of algorithms
encapsulates each algorithm, and
makes the algorithms interchangeable within that family.

We can look at practical implementation in an e-commerce website.
The customer make an order and select a shipping method, based on the shipping method we need to calculate the shipping cost.

The above problem can be solved with strategy pattern.

ClassDiagram1

First we will define an interface that represent our strategy

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StrategyPattern
{
    public interface IShippingStrategy
    {
        double GetShippingCost(Order order);
    }
}

Now we will define the concrete implementation of our strategy

Blue Dart

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StrategyPattern
{
    public class BlueDart : IShippingStrategy
    {
        public double GetShippingCost(Order order)
        {
            return 30.0;
        }
    }
}

Professional

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StrategyPattern
{
    public class Professional:IShippingStrategy
    {
        public double GetShippingCost(Order order)
        {
            return 50.0;
        }
    }
}

India Post

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StrategyPattern
{
    public class IndiaPost:IShippingStrategy
    {
        public double GetShippingCost(Order order)
        {
            return 10.0;
        }
    }
}

Now we will define our context class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StrategyPattern
{
    public class ShippingContext
    {
        private IShippingStrategy _startegy;

        public ShippingContext(IShippingStrategy strategy)
        {
            _startegy = strategy;
        }

        public double GetShippingCostForOrder(Order order)
        {
            return _startegy.GetShippingCost(order);
        }

    }
}

Now we can use our pattern

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StrategyPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, IShippingStrategy> _stratagies = new Dictionary<int, IShippingStrategy>();
            _stratagies.Add(1, new BlueDart());
            _stratagies.Add(2, new Professional());
            _stratagies.Add(3, new IndiaPost());

            Console.WriteLine("Your order created");
            Console.WriteLine("Select Shipping Method");
            Console.WriteLine("-----------------------");
            Console.WriteLine("1. BlueDart");
            Console.WriteLine("2. Professional");
            Console.WriteLine("3. India Post");

            int choice=Convert.ToInt32(Console.ReadLine());

            ShippingContext context = new ShippingContext(_stratagies[choice]);
            Console.WriteLine(context.GetShippingCostForOrder(new Order()).ToString());
            Console.Read();
        }
    }
}

Order class is just a mock class.

Posted in Design Patterns | Tagged: , , | Leave a Comment »

New vending machine at office and Builder Design Pattern

Posted by vivekcek on June 28, 2014

Strong tea is my weakness, I tried all variations of tea’s described in the book ‘A Nice Cup of Tea’ by George Orwell.I recommend a strong tea over beer.

OK come to story, I was looking for a real world example for builder pattern.

So what is this Builder pattern according to GOF.

“Separate the construction of a complex object from its representation so that the same construction process can create different representations.”

Ok so builder pattern deals with construction of objects, that means its a Creational pattern.

I went through some diagrams in internet and found this one useful.

build1

So what you understand from the above image, The definition of builder pattern says we have to reuse the mechanism to construct a complex object.

In the above image the complex object is product, and Director is responsible for creating this product.

So we have to design in such a way to reuse the Director to create different complex objects.

I was looking for a practical example to explain this to my readers. Then my friend Krishna and Mankunnu Subash came to my desk and said there is new vending machine installed at our office. Basically i don’t like the tea or coffee from such machine, because i am a fan of manually prepared tea. Anyway i go out with them.

Woww this is the machine.

build2

Krishna clicked the coffee switch, he got coffee,I think subash clicked the tea button.I selected Cappuccino, It was ok.

Then a bulb blown above my head, yes this machine can be used to explain builder pattern.

I would like to present this machine as a drink preparing machine, So the end product is a drink, which may be either tea or coffee.

build3

First of all our end product drink can be represented by the below class.

class Drink
{
    string _label;

    public Drink(string label)
    {
        this._label = label;
    }

    public override string ToString()
    {
        return this._label;
    }
}

Now i will define an interface.Which represent the process for building a drink.
A tea can be made by mixing hot water and tea powder, coffee can be made by mixing hot water and coffee powder.

interface IDrinkBuilder
{
    void AddWater();
    void AddPowder();
    Drink Drink { get; }
}

Now we will create a concrete tea builder as below.

class TeaBuilder : IDrinkBuilder
{

    Drink drink;

    public TeaBuilder()
    {
        drink = new Drink("Tea");
    }

    public void AddWater()
    {

    }

    public void AddPowder()
    {
        //Tea Powder
    }

    public Drink Drink
    {
        get { return drink; }
    }
}

Then a concrete coffee builder.

class CoffeeBuilder : IDrinkBuilder
{
    Drink drink;

    public CoffeeBuilder()
    {
        drink = new Drink("Coffee");
    }

    public void AddWater()
    {

    }

    public void AddPowder()
    {
        // Coffee powder
    }

    public Drink Drink
    {
        get { return drink; }
    }
}

Now we will design our Director, which can be reused to build a tea or coffee.

class DrinkMaker
{
    public void MakeDrink(IDrinkBuilder builder)
    {
        builder.AddWater();
        builder.AddPowder();
    }
}

You can use the above class in your main as below.

class Program
    {
        static void Main(string[] args)
        {
            DrinkMaker maker;
            IDrinkBuilder builder;

            Console.WriteLine("Enter 'T' for Tea and 'C' for coffee.");
            maker = new DrinkMaker();

            while (true)
            {
                string input = Console.ReadLine();

                if (input == "T")
                {
                    builder = new TeaBuilder();
                    maker.MakeDrink(builder);
                    Console.WriteLine(builder.Drink.ToString() + " is ready.");
                    Console.ReadLine();
                }
                else if (input == "C")
                {
                    builder = new CoffeeBuilder();
                    maker.MakeDrink(builder);
                    Console.WriteLine(builder.Drink.ToString() + " is ready.");
                    Console.ReadLine();
                }
                else
                {
                    Environment.Exit(0);
                }
            }

        }

    }

}

Posted in Design Patterns | Tagged: , , | Leave a Comment »

Simple Factory Vs Factory Method Vs Abstract Factory by Example

Posted by vivekcek on March 17, 2013

I came across lots of situations in which, I have to explain the difference between a Simple Factory, Factory Method and Abstract Factory patterns.

The main objective of this post is how simply you can explain the difference among these patterns using some example. I hope the readers are aware of these patterns, because I am not going to explain each pattern in depth.

Simple Factory Pattern

Definition:
Creates objects without exposing the instantiation logic to the client.
Refers to the newly created object through a common interface

Diagram:

SimpleFactory

Explanation:

The heart of above Simple Factory pattern is the ‘MobileFactory’ class. From the Client when we create an instance of this ‘MobileFactory’, this class will load and cache all the classes that implement the ‘IMobile’ interface by using reflection or some other logic. After that we can call the ‘GetMobile(string Name)’ method in the ‘MobileFactory’ class which will return the specified object through the parameter.

The Client will expect an object that implements the ‘IMobile’ interface.

Factory Method

Definition:

Defines an interface for creating objects, but let subclasses to decide which class to instantiate
Refers the newly created object through a common interface.

Diagram:

FMethod

Explanation:

In Factory Method pattern we will introduce a new interface called ‘IMobileFactory’ and two concrete implementation’s ‘NokiaFactory’ and ‘IphoneFactory’. These concrete classes control the object creation.

In my example the client want a Nokia object. So the steps are given below.

1.The client will load a reference to ‘NokiaFactory’. But Client won’t refer the ‘NokiaFactory’ class directly like the Simple Factory pattern. The client refers the concrete implementation through an interface ‘IMobileFactory’.

2.Then the Client call the ‘CreateMobile()’ method that will return an object of type ‘IMobile’.

3.Here we have to inform the client the concrete implementation to be used through some configuration or parameters.

Abstract Factory

Definition:

Abstract Factory offers the interface for creating a family of related objects, without explicitly specifying their classes

Diagram:

abstractfactorypg

Explanation:

The main point regarding Abstract Factory pattern is that, this pattern creates a family of related objects that have different parent class or interface.

In Abstract Factory pattern the object creation happens in the same way as Factory Method. The only difference is the creation of related objects.

I now updated our old ‘IMobileFactory’ interface with two new methods.
CreateNokiaMobile() – Returns a Nokia objects that implements an ‘INokia’ interface.
CreateAppleMobile()- Returns Iphone objects that implements ‘IApple’ interface.

There are two concrete implementation of ‘IMobileFactory’ named 3GMobileFactory and 4GMobileFactory.

3GMobileFactory – Can return 3G supported mobiles of Nokia and Apple. So as per definition confirms, which returns a family of related objects that have different parents (INokia, IApple).

4GMobileFactory – Can return 4G supported mobiles of Nokia and Apple

Conclusion

By this post my aim was to help you to explain the differences of these three patterns with a simple diagrammatic example.

Posted in Design Patterns | 4 Comments »

Abstract Factory Pattern

Posted by vivekcek on September 15, 2012

Source Code http://sdrv.ms/O4X56A

definition
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

participants

The classes and/or objects participating in this pattern are:

AbstractFactory (IMobileFactory)
declares an interface for operations that create abstract mobiles

ConcreteFactory (IPhoneFactory, NokiaFactory)
implements the operations to create concrete product objects

AbstractProduct (IMobile)
declares an interface for a type of product object

Product (IPhone3,Iphone3gs,Lumia800 etc..)
defines a product object to be created by the corresponding concrete factory
implements the AbstractProduct interface
Client (Program.cs)
uses interfaces declared by AbstractFactory and AbstractProduct classes

Posted in Design Patterns | Leave a Comment »

Factory Method Design Pattern

Posted by vivekcek on September 13, 2012

DOWNLOAD http://sdrv.ms/OrSETl

definition by GOF:

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses

Our Example

The participants classes in this pattern are:

IProduct: defines the interface for objects the factory method creates.

ConcreteProduct: implements the Product interface (ex: Book, Mobile).

IProductFactory: declares an interface with method CreateProduct,Implemented by ConcreteFactory.

ConcreteFactory: overrides the generating method for creating ConcreteProduct objects.(ex: BookFactory, MobileFactory)

All concrete products are implementation of the IProduct, so all of them have the same basic implementation,

In our example class Book and Mobile are concrete implementation of IProduct.

The classes BookFactory and MobileFactory implement IProductFactory. These classes are responsible for creating concrete objects of our Book and Mobile class according to client requirement.

In our example Program.cs is our client class. Client will tell which factory to use. Based on that we get instances of concrete products.

Posted in Design Patterns | Leave a Comment »

Factory Pattern in C#

Posted by vivekcek on September 11, 2012

creates objects without exposing the instantiation logic to the client.
refers to the newly created object through a common interface

The implementation is really simple

1. The client needs a product, but instead of creating it directly using the new operator, it asks the factory object for a new product, providing the information about the type of object it needs.
2.The factory instantiates a new concrete product and then returns to the client the newly created product.
3.The client uses the products as abstract products without being aware about their concrete implementation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;

namespace SimpleFactory
{
    class Program
    {
        static void Main(string[] args)
        {
            ProductFactory factory = new ProductFactory();
            IProduct product = factory.CreateProduct("Book");
        }
    }
    class ProductFactory
    {
        Dictionary<string, Type> Products;
        public ProductFactory()
        {
            LoadProducts();
        }
        public IProduct CreateProduct(string productName)
        {
            Type t = GetType(productName);
            IProduct product = Activator.CreateInstance(t) as IProduct;
            return product;
        }

        private Type GetType(string productName)
        {
            foreach (var product in Products)
            {
                if (Products.Keys.Contains(productName))
                    return Products[product.Key];
            }
            return null;
        }
        private void LoadProducts()
        {
            Products = new Dictionary<string, Type>();
            Type[] produtTypes = Assembly.GetExecutingAssembly().GetTypes();
            foreach (Type product in produtTypes)
            {
                if (product.GetInterface(typeof(IProduct).ToString()) != null)
                    Products.Add(product.Name.ToString(), product);
            }
        }
    }
    interface IProduct
    {
        string ProductName { get; }
    }
    class Book : IProduct
    {

        public string ProductName
        {
            get { return "Book"; }
        }
    }
    class MobilePhone : IProduct
    {

        public string ProductName
        {
            get { return "MobilePhone"; }
        }
    }
}

Posted in Design Patterns | Leave a Comment »

Chain Of Responsibility Design Pattern in C#

Posted by vivekcek on September 10, 2012

read about it here http://www.dofactory.com/Patterns/PatternChain.aspx#_self2

Here i am giving a simple example from my organization.
In our organization if i need a leave i have to submit a leave form to someone just above me. The person just above me is my mentor.If i need a leave for 1 day he can immediately approve my leave. If i need more than 1 day he will contact Project manger he is just above the mentor. The project manger can approve leave upto 2 days.If i need leave more than 2 days, the project manger consult HR Manger.HR Manger can approve leave up-to 4 days.If i request more than 4 days leave my request will be forwarded to CEO. CEO will approve leave’s up-to 5 days.If i need more than 5 day’s of leave CEO will call me for a meeting.

In all the above case i just need to submit leave application to my mentor. The approval process propagate automatically and i will get some response.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChainOfResponsibility
{
    class Program
    {
        static void Main(string[] args)
        {
            int NumberOfDays;
            var vivek = new SoftwareEngineer();
            var myMentor = new Mentor();
            var myPM = new ProjectManger();
            var myHR = new HRManger();
            var myCEO = new CEO();

            vivek.SetNextLevelEmployee(myMentor);
            myMentor.SetNextLevelEmployee(myPM);
            myPM.SetNextLevelEmployee(myHR);
            myHR.SetNextLevelEmployee(myCEO);

            while (true)
            {
                Console.WriteLine("Enter Number Of Day's Of Leave");
                NumberOfDays = int.Parse(Console.ReadLine());
                vivek.ProcessLeave(NumberOfDays);
            }

        }
    }
    public abstract class Employee
    {
        protected Employee NextLevelEmployee;
        public abstract void ProcessLeave(int numberOfDays);
        public void SetNextLevelEmployee(Employee emp)
        {
            NextLevelEmployee = emp;
        }
    }
    public class SoftwareEngineer : Employee
    {

        public override void ProcessLeave(int numberOfDays)
        {
            if (NextLevelEmployee != null)
            {
                NextLevelEmployee.ProcessLeave(numberOfDays);
            }
        }
    }
    public class Mentor : Employee
    {

        public override void ProcessLeave(int numberOfDays)
        {
            if(numberOfDays<2)
            {
                Console.WriteLine("Leave approved by Mentor");
            }
            else if (NextLevelEmployee != null)
            {
                NextLevelEmployee.ProcessLeave(numberOfDays);
            }
        }
    }
    public class ProjectManger : Employee
    {

        public override void ProcessLeave(int numberOfDays)
        {
            if (numberOfDays <=3)
            {
                Console.WriteLine("Leave approved by Project Manger");
            }
            else if (NextLevelEmployee != null)
            {
                NextLevelEmployee.ProcessLeave(numberOfDays);
            }
        }
    }
    public class HRManger : Employee
    {

        public override void ProcessLeave(int numberOfDays)
        {
            if (numberOfDays <=4)
            {
                Console.WriteLine("Leave approved by HRMnager");
            }
            else if (NextLevelEmployee != null)
            {
                NextLevelEmployee.ProcessLeave(numberOfDays);
            }
        }
    }
    public class CEO : Employee
    {

        public override void ProcessLeave(int numberOfDays)
        {
            if (numberOfDays <= 5)
            {
                Console.WriteLine("Leave approved by CEO");
            }
            else 
            {
                Console.WriteLine("Let us have a meeting with CEO");
            }
        }
    }
}

Posted in Design Patterns | Leave a Comment »

Facade Pattern

Posted by vivekcek on September 8, 2012

A facade is an object that provides a simplified interface to a larger body of code, such as a class library.
Look at the example below where the ‘SoftwareCompany’ abstract the building step of a software.

Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Facade
{
    class Program
    {
        static void Main(string[] args)
        {
            SoftwareCompany comp = new SoftwareCompany();
            comp.BuildSoftware();
            Console.ReadLine();
        }
            
    }
    /// <summary>
    /// Abstract the building of a software
    /// </summary>
    class SoftwareCompany
    {
        private RequirementAnalysis rqAnlysis = null;
        private Design design = null;
        private Coding coding = null;
        private Testing testing = null;
        private Deploying deploy = null;
        public SoftwareCompany()
        {
            rqAnlysis = new RequirementAnalysis();
            design = new Design();
            coding = new Coding();
            testing = new Testing();
            deploy = new Deploying();
        }
        public void BuildSoftware()
        {
            rqAnlysis.DoRequirementAnalysis();
            design.DoDesign();
            coding.DoCoding();
            testing.DoTesting();
            deploy.DoDeploying();
        }
    }
    class RequirementAnalysis
    {
        public void DoRequirementAnalysis()
        {
            Console.WriteLine("RequirementAnalysis");
        }
    }
    class Design
    {
        public void DoDesign()
        {
            Console.WriteLine("Design");
        }
    }
    class Coding
    {
        public void DoCoding()
        {
            Console.WriteLine("Coding");
        }
    }
    class Testing
    {
        public void DoTesting()
        {
            Console.WriteLine("Testing");
        }
    }
    class Deploying
    {
        public void DoDeploying()
        {
            Console.WriteLine("Deploying");
        }
    }
}

Posted in Design Patterns | Leave a Comment »

Singleton – Normal-Thread Safe-Lazy

Posted by vivekcek on September 8, 2012

Ensure that only one instance of a class is created.
Provide a global point of access to the object

Not Thread Safe Implementation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Singleton
{
    class Program
    {
        static void Main(string[] args)
        {
           Console.WriteLine(Singleton.Instance.DoSomething("Hay"));
           Console.WriteLine(Singleton.Instance.DoSomething("Halo"));
           Console.ReadLine();
        }
    }

    /// <summary>
    /// Not thread safe single implementation
    /// </summary>
    public class Singleton
    {
        /// <summary>
        /// Private variable hold the instance.
        /// </summary>
        private static Singleton _Instance = null;

        /// <summary>
        /// Private constructor to prevent direct instance creation.
        /// </summary>
        private Singleton() { }

        /// <summary>
        /// The only entry point to get an instance of the class.
        /// </summary>
        public static Singleton Instance
        {
            get
            {
                if (_Instance == null)
                {
                    _Instance = new Singleton();
                    return _Instance;
                }
                else
                    return _Instance;
            }
        }

        /// <summary>
        /// Some Functionality.Hash code indicate same instance.
        /// </summary>
        /// <returns></returns>
        public string DoSomething(string param)
        {
            return param + "from " + _Instance.GetHashCode();
        }


    }
}

Thread Safety By Double Lock

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Singleton
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Singleton.Instance.DoSomething("Hay"));
            Console.WriteLine(Singleton.Instance.DoSomething("Halo"));
            Console.ReadLine();
        }
    }

    /// <summary>
    /// Not thread safe single implementation
    /// </summary>
    public class Singleton
    {
        private static readonly object _SyncLock = new object();
        /// <summary>
        /// Private variable hold the instance.
        /// </summary>
        private static Singleton _Instance = null;

        /// <summary>
        /// Private constructor to prevent direct instance creation.
        /// </summary>
        private Singleton() { }

        /// <summary>
        /// The only entry point to get an instance of the class.
        /// </summary>
        public static Singleton Instance
        {
            get
            {

                if (_Instance == null)
                {
                    lock (_SyncLock)
                    {
                        if (_Instance == null) //Double check
                            _Instance = new Singleton();
                    }

                }
                return _Instance;
            }
        }

        /// <summary>
        /// Some Functionality.Hash code indicate same instance.
        /// </summary>
        /// <returns></returns>
        public string DoSomething(string param)
        {
            return param + "from " + _Instance.GetHashCode();
        }


    }
}

Singleton lazy instantiation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Singleton
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Singleton.Instance.DoSomething("Hay"));
            Console.WriteLine(Singleton.Instance.DoSomething("Halo"));
            Console.ReadLine();
        }
    }

    /// <summary>
    /// Not thread safe single implementation
    /// </summary>
    public class Singleton
    {
                
        /// <summary>
        /// Private constructor to prevent direct instance creation.
        /// </summary>
        private Singleton() { }

        /// <summary>
        /// The only entry point to get an instance of the class.
        /// </summary>
        public static Singleton Instance
        {
            get { return Nested.Instance; }
        }

        /// <summary>
        /// Some Functionality.
        /// </summary>
        /// <returns></returns>
        public string DoSomething(string param)
        {
            return param ;
        }

        /// <summary>
        /// Nested class for lazy
        /// </summary>
        private class Nested
        {
            static Nested()
            { }
            internal static readonly Singleton Instance = new Singleton();
        }


    }
}

Posted in Design Patterns | Tagged: , | Leave a Comment »