09 August, 2012

Strategy Design Pattern


Strategy design pattern is a behavioral design pattern. It is a particular software design pattern where algorithms are selected at runtime.

According to the book of Design Pattern (Gang of Four) - “Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. “

The key phrases of definition are "Family of algorithms", "encapsulate", and "interchangeable". Actually, Strategy Pattern encapsulates a collection of functions that do similar yet not identical jobs. Client is not bound to call fixed methods; rather it can change its strategy dynamically at run time. Client don’t call any methods directly by instantiating concrete classes. It sets its strategy via context class.

There are three main parts in strategy pattern:

1.       Strategy – An interface that defines how the algorithm will be called.
2.       Concrete Strategy – The implementation of the strategy.
3.       Context – It holds the concrete strategy.

 


Implementation:
Suppose you have two lists of items. Item here integer numbers. Now, if you want to search an item from either of the lists. You can use either one of the algorithms from Linear Search or Binary search. Since binary search algorithm cannot search data without sorted list, we take here a sorted list. Now the strategy of client to use which one – Binary search or linear search. Let’s implement the problem by strategy pattern using c#.


Step 1: Create an Interface for Strategy

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

namespace StrategyPattern
{
    /// 
    /// Strategy defines how algorithm will be called
    /// 
    public interface ISearchStrategy
    {
        int Search(int[] list, int item);
    }
}


Step 2: Create concrete strategy (Linear Search)

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

namespace StrategyPattern
{
    /// 
    /// Concrete strategy(Linear Search Algorithm)
    /// 
    public class LinearSearch : ISearchStrategy
    {
        #region ISearchStrategy Members

        public int Search(int[] list, int item)
        {
            Console.WriteLine("Linear Search");
            int position = 0;

            for (int i = 0; i < list.Count(); i++)
            {
                if (list[i] == item)
                {
                    position = i;
                    break;
                }
            }

            return position;
        }

        #endregion
    }
}

Step 3: Create concrete strategy (Binary Search)

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

namespace StrategyPattern
{
    /// 
    /// Concrete strategy(Binary Search Algorithm)
    /// 
    public class BinarySearch : ISearchStrategy
    {
        #region ISearchStrategy Members

        public int Search(int[] list, int item)
        {
            Console.WriteLine("Binary Search");

            int beg = 0;
            int end = list.Count() - 1;
            int mid = (int)((beg + end)/2);
            int position = 0;

            while (beg <= end && list[mid] != item)
            {
                if(item < list[mid])
                    end = mid - 1;
                else
                    beg = mid + 1;

                mid = (int)((beg + end)/2);
            }

            if (list[mid] == item)
                position = mid;
            else
                position = 0;


            return position;
        }

        #endregion
    }
}

 
Step 4: Create a context class

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

namespace StrategyPattern
{
    /// 
    /// Concrete strategy(Linear Search Algorithm)
    /// 
    public class LinearSearch : ISearchStrategy
    {
        #region ISearchStrategy Members

        public int Search(int[] list, int item)
        {
            Console.WriteLine("Linear Search");
            int position = 0;

            for (int i = 0; i < list.Count(); i++)
            {
                if (list[i] == item)
                {
                    position = i;
                    break;
                }
            }

            return position;
        }

        #endregion
    }
}


Step 5: Client class to demonstrate strategy pattern

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

namespace StrategyPattern
{
    /// 
    /// Client class
    /// 
    class Program
    {
        static void Main(string[] args)
        {

            int[] sortedList = { 1, 2, 3, 4, 5, 6, 7, 8 };

            //Instance of context to follow different strategies
            SearchList objSearchList = new SearchList();

            objSearchList.SetSearchStrategy(new BinarySearch());
            objSearchList.Search(sortedList, 4);

            objSearchList.SetSearchStrategy(new LinearSearch());
            objSearchList.Search(sortedList, 7);

            Console.ReadLine();
        }
    }
}


Output:

08 August, 2012

Decorator Design Pattern


You who work on design pattern must familiar with Gang of Four (GoF). Design Patterns: Elements of Reusable Object-Oriented Software is a Software Engineering book. The authors of this book are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. The authors of this book are often refers to as Gang of Four (GoF).  It’s a parody relating to Mao’s Gang of Four. This book describes the recurring solution of common problem in software design. The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral. Factory Pattern, Abstract Factory Pattern, Singleton Pattern, Builder e.t.c are creational design pattern. Decorator, Adapter, Bridge, Fa├žade, Proxy, Composite e.t.c are structural design pattern. Command, interpreter, strategy, iterator e.t.c are behavioral design pattern.

Decorator Design Pattern
Decorator Design Pattern is a structural design pattern. It is also known as wrapper. It is used to add additional functionality to a particular object during run time without affecting other objects. Responsibility can be adding or removing at run time. Critics says that it uses lot of little object of similar type.

Let’s consider a scenario in which I am going to implement Decorated Design Pattern. We, Bangladeshi are very much cricket loving. A cricket equipment shop declared some package on the occasion of Cricket World Cup 2011. The base package is with a bat and a ball and its cost is 1500 Taka (Bangladeshi Currency). The smart package is with a bat, a ball and 6 stamps i.e base package plus 6 stamps and its cost is 1500 + 600 = 2100 Taka. The special package is with a bat, a ball, 6 stamps and a pair of gloves i.e smart package plus a pair of gloves. It’s cost is 2100 + 500 = 2600 Taka. It looks like the following figure. Actually, the top one wrapped the inner packages.


 

Before going to implement the scenario by decorated design pattern, I would like to show you the class diagram. The class diagram is given below.



 

Implementation: Let’s implement decorated design pattern by C#.

Step 1: Create interface ICricketInstrument for all package of cricket instrument.

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

namespace DecoratorPattern
{
    /// 
    /// Interface for Cricket Instrument
    /// Developed by: Mahedee
    /// 
    public interface ICricketInstrument
    {
        double Cost { get; }
        string Insturments { get; }
    }
}


Step 2: Create a base type for Concrete Cricket Instrument Package and Instrument Package Option
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
    /// 
    /// Base type for concrete cricket instrument package and decorator(option).
    /// Developed by: Mahedee
    /// 
    public abstract class CricketInstrument : ICricketInstrument
    {
        private double cost = 00;
        private string instrument = "Cricket Instruments: ";

        #region ICricketInstrument Members

        public virtual double Cost
        {
            get { return cost; }
        }

        public virtual string Insturments
        {
            get { return instrument; }
        }

        #endregion
    }
}


Step 3: Create a base type for Concrete Cricket Instrument Package Option. It is actually decorator – to decorate Instrument package.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
    /// 
    /// Base type or decorator for concrete cricket instrument package.
    /// Developed by: Mahedee
    /// 
    public abstract class CricketInstrument : ICricketInstrument
    {
        private double cost = 00;
        private string instrument = "Cricket Instruments: ";

        #region ICricketInstrument Members

        public virtual double Cost
        {
            get { return cost; }
        }

        public virtual string Insturments
        {
            get { return instrument; }
        }

        #endregion
    }
}


Step 4: Create base package of Cricket Instrument.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
    /// 
    /// Base Cricket Insturment Package
    /// 
    public class BasePackage : CricketInstrument
    {
        double cost = 1500;
        string instruments = "Ball and Bat";

        public override double Cost
        {
            get { return cost; }
        }

        public override string Insturments
        {
            get { return base.Insturments + instruments; }
        }

    }
}


Step 5: Decorate Smart package for Cricket Instrument
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
    /// 
    /// Smart Package = Base Package (Bat, Ball) + 6 Stamps
    /// Developed by: Mahedee
    /// 
    public class SmartPackage : PackageOption
    {
        double cost = 600;
        string instruments = "6 Stamps";
        CricketInstrument objCricketInstrument;

        public SmartPackage(CricketInstrument objPCricketInstrument)
        {
            objCricketInstrument = objPCricketInstrument;
        }

        public override double Cost
        {
            get { return objCricketInstrument.Cost + cost; }
        }

        public override string Insturments
        {
            get { return objCricketInstrument.Insturments + ", " + instruments; }
        }
    }
}


Step 6: Decorate Special Package for Cricket Instrument.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
    /// 
    /// Special Package = Base Package (Bat, Ball) + 6 Stamps + 1 Pair - Gloves
    /// Developed by: Mahedee
    /// 
    public class SpecialPackage : PackageOption
    {
        double cost = 500;
        string instruments = "Gloves - 1 Pair";
        CricketInstrument objCricketInstrument;

        public SpecialPackage(CricketInstrument objPCricketInstrument)
        {
            objCricketInstrument = objPCricketInstrument;
        }

        public override double Cost
        {
            get { return objCricketInstrument.Cost + cost; }
        }

        public override string Insturments
        {
            get { return objCricketInstrument.Insturments + ", " + instruments; }
        }

    }
}



Step 7: Program class to create base package and decorate other package with option.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
    public class Program
    {
        static void Main(string[] args)
        {
            //Base Insturment class

            CricketInstrument objCricketInstruments = new BasePackage();
            Console.WriteLine("::Base Package::");
            Console.WriteLine(objCricketInstruments.Insturments);
            Console.WriteLine("Instrument's Cost: " + objCricketInstruments.Cost);

            Console.WriteLine();

            //Smart Package
            objCricketInstruments = new SmartPackage(objCricketInstruments);
            Console.WriteLine("::Smart Package::");
            Console.WriteLine(objCricketInstruments.Insturments);
            Console.WriteLine("Instrument's Cost: " + objCricketInstruments.Cost);

            Console.WriteLine();

            //Special Package
            objCricketInstruments = new SpecialPackage(objCricketInstruments);
            Console.WriteLine("::Special Package::");
            Console.WriteLine(objCricketInstruments.Insturments);
            Console.WriteLine("Instrument's Cost: " + objCricketInstruments.Cost);

            Console.ReadLine();


        }
    }
}

04 August, 2012

Abstract Factory Pattern

Abstract factory pattern is a creational design pattern. Creational design pattern is deals with object creation mechanism. Object creation mechanism is changed on the basis of problem. Abstract factory pattern provides an interface to create families of related or dependent objects without specifying their concrete class. It is identified on the basis of problem complexity. It is encapsulated the process of instantiation of family of classes. Abstract factory pattern is widely used in framework and libraries to encapsulate the family of classes.

Elements of Abstract Factory Pattern:
1.       Abstract Factory – An Interface to create families of related or dependent item object.
2.       Concrete Factory – Implement the interface to create families of related item object.
3.       Abstract Item – An interface to create concrete item object.
4.       Concrete Item – Implement the interface to create concrete item object.
5.       Client – Uses Interface (abstract Item) provided by abstract factory and access concrete object by this interface.

Implementation:
Here I implemented abstract factory pattern in International Cricket Team by C#. The UML diagram is given below.



Step 1:  Create interface for Item class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{
    /// 
    /// Interface for Item class
    /// 
    
    public interface ICricketer
    {
        string BattingStrength();
        string BowlingStrength();
        string AllroundingStrength();
        string IconPlayer();
    }
}



Step 2: Create Factory Interface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{
    /// 
    /// A Factory interface
    /// 
    public interface ICricketerFactory
    {
        ICricketer GetCricketer(CricketerBase cricketerBase); 
    }
}


Step 3: Define the type of Base object
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

    /// 
    /// Define the type of Base Object
    /// 
    public enum CricketerBase
    {
        AustralianCricketer,
        BangladeshiCricketer,
        EnglishCricketer,
        IndianCricketer,
        PakistaniCricketer
    }

}



Step 4: Create Concrete factory class for Asian Cricketer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

    /// 
    /// Concrete factory class for Asian Cricketer
    /// 
    
    public class AsianCricketerFactory : ICricketerFactory
    {

        #region ICricketerFactory Members

        public ICricketer GetCricketer(CricketerBase cricketerBase)
        {
            ICricketer objICricketer = null;

            switch (cricketerBase)
            {
                case CricketerBase.BangladeshiCricketer:
                    objICricketer = new BangladeshiCricketer();
                    break;
                case CricketerBase.IndianCricketer:
                    objICricketer = new IndianCricketer();
                    break;
                default:
                    break;
            }
            return objICricketer;
        }

        #endregion
    }
}


Step 5: Create Concrete factory class for European Cricketer

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

namespace AFP
{
    /// 
    /// Concrete factory class for European Cricketer
    /// 
    
    public class EuropeanCricketerFactory : ICricketerFactory
    {

        #region ICricketerFactory Members

        public ICricketer GetCricketer(CricketerBase cricketerBase)
        {
            ICricketer objICricketer = null;

            switch (cricketerBase)
            {
                case CricketerBase.EnglishCricketer:
                    objICricketer = new EnglishCricketer();
                    break;
                default:
                    break;
            }
            return objICricketer;
        }

        #endregion
    }
}


Step 6: Create Item class for Bangladeshi Cricketer

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

namespace AFP
{

    /// 
    /// Item class for Bangladeshi Cricketer
    /// 
    
    public class BangladeshiCricketer : ICricketer
    {
        #region ICricketer Members

        public string BattingStrength()
        {
            return "60%";
        }

        public string BowlingStrength()
        {
            return "70%";
        }

        public string AllroundingStrength()
        {
            return "85%";
        }

        public string IconPlayer()
        {
            return "Shakib Al Hasan";
        }

        #endregion
    }
}


Step 7: Create Item Class for Indian Cricketer

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

namespace AFP
{

    /// 
    /// Item class for Indian Cricketer
    /// 
    
    public class IndianCricketer : ICricketer
    {

        #region ICricketer Members

        public string BattingStrength()
        {
            return "85%";
        }

        public string BowlingStrength()
        {
            return "60%";
        }

        public string AllroundingStrength()
        {
            return "70%";
        }

        public string IconPlayer()
        {
            return "Shachin Tendulkar.";
        }

        #endregion
    }
}


Step 8: Create Item class for Pakistani Cricketer

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

namespace AFP
{

    /// 
    /// Item class for Pakistani Cricketer
    /// 
    
    public class PakistaniCricketer : ICricketer
    {

        #region ICricketer Members

        public string BattingStrength()
        {
            return "75%";
        }

        public string BowlingStrength()
        {
            return "85%";
        }

        public string AllroundingStrength()
        {
            return "75%";
        }

        public string IconPlayer()
        {
            return "Shahid Afridi.";
        }

        #endregion
    }
}


Step 9: Create Item class for English Cricketer

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

namespace AFP
{

    /// 
    /// Item class for English Cricketer
    /// 
   
    public class EnglishCricketer : ICricketer
    {

        #region ICricketer Members

        public string BattingStrength()
        {
            return "75%";
        }

        public string BowlingStrength()
        {
            return "80%";
        }

        public string AllroundingStrength()
        {
            return "70%";
        }

        public string IconPlayer()
        {
            return "Kavin Pietersen";
        }

        #endregion
    }
}


Step 10: Create a client class

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

namespace AFP
{

    /// 
    /// Client Class
    /// 
    
    class Program
    {
        static void Main(string[] args)
        {
            AsianCricketerFactory objAsianFactory = new AsianCricketerFactory();
            ICricketer objIAsianCricketer = objAsianFactory.GetCricketer(CricketerBase.BangladeshiCricketer);
            Console.WriteLine("Bangladesh Cricket Team\nBatting Strength:" + objIAsianCricketer.BattingStrength());
            Console.WriteLine("Bowling Strength:" + objIAsianCricketer.BowlingStrength());
            Console.WriteLine("Allrounding Strength:" + objIAsianCricketer.AllroundingStrength());
            Console.WriteLine("Icon Player:" + objIAsianCricketer.IconPlayer());

            Console.WriteLine();

            EuropeanCricketerFactory objEuropeanFactory = new EuropeanCricketerFactory();
            ICricketer objIEuropeanCricketer = objEuropeanFactory.GetCricketer(CricketerBase.EnglishCricketer);
            Console.WriteLine("England Cricket Team\nBatting Strength:" + objIEuropeanCricketer.BattingStrength());

            Console.WriteLine("Bowling Strength:" + objIEuropeanCricketer.BowlingStrength());
            Console.WriteLine("Allrounding Strength:" + objIEuropeanCricketer.AllroundingStrength());
            Console.WriteLine("Icon Player:" + objIEuropeanCricketer.IconPlayer());


            Console.ReadLine();


        }
    }
}


Step 11: Output