Monday 30 May 2011

Design Pattern


Design patterns are recurring solutions to software design problems you find again and again in real-world application development. Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges.
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.
Creational Design Pattern: This design pattern focuses on how object are created and utilised in an application. They tackle the aspects of when and how objects are created, keeping in mind what’s the best way these objects should be created.
Some commonly known Creational Design Patterns are
a.      Abstract Factory Pattern: This pattern is used to create concrete class instances without specifying the exact class type. The Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme. Abstract Factory Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
Example: Let’s take example for developing web and windows application control. We have factory for Button controls having Web Button, Windows Button and we have factory for Textbox control Web Textbox, Windows Textbox.  Now I want to create object for web or windows without specifying there concrete classes. In this situation I will use abstract factory.


namespace DesignPatterns.Creational.AbstractFactory
{
   

    #region " Abstract classes for Common Controls"

    /// <summary>
    ///  abstrct class MyButton
    /// </summary>
    public abstract class MyButton
    {
        //Method to get Button Information.
        public abstract void GetInformation();
    }

    /// <summary>
    ///  Abstract class Textbox.
    /// </summary>
    public abstract class MyTextBox
    {
        //Method to get Textbox Information.
        public abstract void GetInformation();

    }

    #endregion

    #region " To Create the Windows or Web Controls "

    #region " Windows Controls"
   
    /// <summary>
    ///  Windows button Class which inherits MyButton Class
    /// </summary>
    public class WindowsButton : MyButton
    {
        //override the MyButton class method.
        public override void GetInformation()
        {
            Console.WriteLine("Windows Button");
        }
    }

    /// <summary>
    /// windows textbox class which inherits MyTextbox class.
    /// </summary>
    public class WindowsTextBox : MyTextBox
    {
        //override the MyTextbox class method.
        public override void GetInformation()
        {
            Console.WriteLine("Windows TextBox");
        }
    }
   
    #endregion

    #region " Web Controls"

    /// <summary>
    ///  Web button Class which inherits MyButton Class
    /// </summary>
    public class WebButton : MyButton
    {
        //override the MyButton class method.
        public override void GetInformation()
        {
            Console.WriteLine("Web Button");
        }
    }

    /// <summary>
    /// Web textbox class which inherits MyTextbox class.
    /// </summary>
    public class WebTextBox : MyTextBox
    {
        //override the MyTextbox class method.
        public override void GetInformation()
        {
            Console.WriteLine("Web TextBox");
        }
    }

    #endregion

    #endregion

    #region " Control Factory"

    /// <summary>
    ///  Abstract Class  ControlFactory which contain abstract Method to Create Button and Textbox.
    ///  The methods will return the object of MyButton and MyTextbox class.
    /// </summary>
    public abstract class MyControlFactory
    {
        // metod which will return MyButton object.
        public abstract MyButton CreateButton();

        // metod which will return MyTextBox Object
        public abstract MyTextBox CreateTexbox();
    }

    // Concrete Windows Factory Class.
    public class WindowsFactory : MyControlFactory
    {
        public override MyButton CreateButton()
        {
            //object of windowsbutton class    
            return new WindowsButton();
        }
        public override MyTextBox CreateTexbox()
        {
//object of windowstextbox class
            return new WindowsTextBox();
        }
    }
    // Concrete Web Factory Class.
    public class WebFactory : MyControlFactory
    {
        public override MyButton CreateButton()
        {
//object of Webbutton class
            return new WebButton();
        }
        public override MyTextBox CreateTexbox()
        {
//object of webtextbox class
            return new WebTextBox();
        }
    }

    #endregion


    #region " Client Class"

    public class MyApplicationClass
    {
        private MyButton button;
        private MyTextBox textbox;

        /// <summary>
        ///  Constructor of MyApplicationClass
        /// </summary>
        /// <param name="objControlfactory">object of MyControlfactory(Windows or Web)</param>
        public MyApplicationClass(MyControlFactory objControlfactory)
        {
            this.button = objControlfactory.CreateButton();
            this.textbox = objControlfactory.CreateTexbox();
        }

        /// <summary>
        ///  To get the informaiton about the controls.
        /// </summary>
        public void GetInformation()
        {
            this.button.GetInformation();
            this.textbox.GetInformation();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            WindowsFactory objWindows = new WindowsFactory();
            MyApplicationClass objapplication = new MyApplicationClass(objWindows);
            objapplication.GetInformation();

            WebFactory objWeb = new WebFactory();
            MyApplicationClass objWebapplication = new MyApplicationClass(objWeb);
            objWebapplication.GetInformation();
        }
    }

    #endregion

}


b.      Builder Pattern:  Separate the construction of a complex object from its representation so that the same construction process can create different representations. This is useful because the same method that deals with construction of the object can be used to construct different design constructs.
Example: Let’s take an example of Construction Company. If a builder wants to build a glass house then the required parts are glass floor, glass walls, glass doors and glass windows. Same way if he wants to build a wooden house then the required parts are wooden floor, wooden walls, wooden door and windows. Now the developer will bring the raw material and make the parts (glass windows or wooden windows) as per his requirements. Once the part development process will completed, the developer will build the house.

namespace DesignPatterns.Creational.Builder
{
    // House Part class
    public class HousePart
    {
        #region " Private Variables"
       
        private string strPartName;
       
        #endregion

        #region " Properties"

        public string PartName
        {
            get
            {
                return this.strPartName;

            }
        }

        #endregion

        #region " Constructor"

        public HousePart(string partname)
        {
            this.strPartName = partname;
        }

        #endregion

    }

    public class House
    {
        #region " Private Variables"
       
        private string strMaterial;
        private List<HousePart> objHousePart;

        #endregion

        #region " Properties"

        public string Material
        {
            get
            {
                return this.strMaterial;
            }
        }

        #endregion

        #region " Constructor"
      
        /// <summary>
        /// construct the new house with given material.
        /// </summary>
        /// <param name="material">House material</param>
        public House(string material)
        {
            this.strMaterial = material;
            this.objHousePart = new List<HousePart>();

        }

        #endregion

        #region " Methods"

        /// <summary>
        ///  To add the parts.
        /// </summary>
        /// <param name="parts">object of house Part.</param>
        public void AddParts(HousePart parts)
        {
            this.objHousePart.Add(parts);
        }

        public override string ToString()
        {
            return string.Format("{0},\n{1}\n{2},\n{3},\n{4}", this.strMaterial, this.objHousePart[0].PartName, this.objHousePart[1].PartName, this.objHousePart[2].PartName, this.objHousePart[3].PartName);
        }
        #endregion

    }

    public abstract class HouseBuilder
    {
        #region " variables"

        // Protected variable - object of house

        protected House objHouse;

        #endregion

        #region " Properties"

        // Protected variable

        public House House
        {
            get
            {
                return this.objHouse;
            }
        }

        #endregion

        #region "Abstract Methods"

        public abstract void BuildDoors();
        public abstract void BuildWindows();
        public abstract void BuildWalls();
        public abstract void BuildFloor();
        public abstract House GetHouse();


        #endregion
    }

    // class inherited form House Builder class.
    public class GlassHouseBuilder: HouseBuilder
    {
        public override void BuildFloor()
        {
            objHouse = new House("GlassHouse");
            House.AddParts(new HousePart("..Stone Floor"));

        }
        public override void BuildWalls()
        {
            House.AddParts(new HousePart(House.Material + "..Walls"));
        }
        public override void BuildWindows()
        {
            House.AddParts(new HousePart(House.Material + "..Windows"));

        }

        public override void BuildDoors()
        {
            House.AddParts(new HousePart("..Wood Door"));

        }
        public override House GetHouse()
        {
            return objHouse;
        }
       
    }

    public class Contractor
    {
        public void  Construct(HouseBuilder housebuilder)
        {
            housebuilder.BuildFloor();
            housebuilder.BuildWalls();
            housebuilder.BuildDoors();
            housebuilder.BuildWindows();

        }

    }
}
class Program
    {
        static void Main(string[] args)
        {
           

            Contractor objContractor = new Contractor();
            GlassHouseBuilder objGlasshouse = new GlassHouseBuilder();
            objContractor.Construct(objGlasshouse);
            House objHouse = objGlasshouse.GetHouse();
            Console.WriteLine(objHouse);


           
        }
}
c.       Factory Pattern: provide interface to create object, but let sub class decide whose object will be created. In other words creating object without exposing the instantiation logic to client.
Example: In real time example bank has many account type like Saving, Current and Fixed accounts. All account type has different type of facilities.

namespace DesignPatterns.Creational.FactoryMethod
{
  

    // Abstract class Fascilites -
    public abstract class Fascilities
    {
        // Method to get the Fascilities
        public abstract void GetData();
    }

    public class ATM : Fascilities
    {

        public override void GetData()
        {
            Console.WriteLine("ATM");
        }
    }
   
    // Cheque class inherits Fascilities class.
    public class Cheque : Fascilities
    {
        public override void GetData()
        {
            Console.WriteLine("Cheque");
        }
    }

    public class Deposit : Fascilities
    {
        public override void GetData()
        {
            Console.WriteLine("Deposited");
        }
    }
   
    public class Interest : Fascilities
    {
        public override void GetData()
        {
            Console.WriteLine("Interest Given");
        }
    }

    // OverDue class inherits Fascilities class.
    public class OverDue : Fascilities
    {
        public override void GetData()
        {
            Console.WriteLine("Overdraft Given");
        }
    }

    public class Widthdrawal : Fascilities
    {
        public override void GetData()
        {
            Console.WriteLine("Widthdrawl");
        }
    }

    // Abstract Class account.
    public abstract class Account
    {

        private List<Fascilities> fascilities = new List<Fascilities>();

        // Property
        public List<Fascilities> AccountFascliites
        {
            get
            {
                return this.fascilities;

            }
        }

        // Constructor

        public Account()
        {
            // call the method get properties.
            GetFacilites();
            DisplayFascilities();
        }

        public abstract void GetFacilites();

        public abstract void DisplayFascilities();



    }

    public class Current : Account
    {
        public override void GetFacilites()
        {
            base.AccountFascliites.Add(new Deposit());
            base.AccountFascliites.Add(new Widthdrawal());
            base.AccountFascliites.Add(new Cheque());
            base.AccountFascliites.Add(new OverDue());
        }
        public override void DisplayFascilities()
        {
            Console.WriteLine(" Current Account Fascilities");
            base.AccountFascliites[0].GetData();
            base.AccountFascliites[1].GetData();
            base.AccountFascliites[2].GetData();
            base.AccountFascliites[3].GetData();

        }
    }

    public class Fixed : Account
    {
        public override void GetFacilites()
        {
            base.AccountFascliites.Add(new Interest());
            base.AccountFascliites.Add(new Deposit());
            base.AccountFascliites.Add(new Widthdrawal());
        }
        public override void DisplayFascilities()
        {
            Console.WriteLine(" Fixed Account Fascilities");
            base.AccountFascliites[0].GetData();
            base.AccountFascliites[1].GetData();
            base.AccountFascliites[2].GetData();

        }
    }

    public class Savings : Account
    {
        public override void GetFacilites()
        {
            base.AccountFascliites.Add(new Interest());
            base.AccountFascliites.Add(new Deposit());
            base.AccountFascliites.Add(new Widthdrawal());
            base.AccountFascliites.Add(new Cheque());
            base.AccountFascliites.Add(new ATM());


        }
        public override void DisplayFascilities()
        {
            Console.WriteLine(" Saving Account Fascilities");
            base.AccountFascliites[0].GetData();
            base.AccountFascliites[1].GetData();
            base.AccountFascliites[2].GetData();
            base.AccountFascliites[3].GetData();
            base.AccountFascliites[4].GetData();
        }
    }

}
class Program
    {
        static void Main(string[] args)
        {
           

            Savings saving = new Savings();
            Console.WriteLine(Environment.NewLine);
            Fixed fiexe = new Fixed();
            Console.WriteLine(Environment.NewLine);
            Current current = new Current();


           
        }
}



d.      Prototype Pattern: prototype design patter is also a pattern we use to receive an object instance for a particular class, such as builder and factory pattern. Instead of having a new fresh object every time, we can make a copy of an existed object instantly (object we can use as Prototype) and start using it. In that way, we do not have to repeat the building process for the object we are trying to use. The new copy object is totally independent with the original prototype object, and can be used for any purpose that will not affect the original. There is no limit for copying the existing objects; any existing object can be copied.
Example: When the builder wants to build a house he will go with the Builder Pattern which makes his work easy. Purchase of raw material, creation of parts and making a house. Next time the developer wants to make the glass house he need to go over the same steps again and again .Finally he was tired of doing this so he asked me is there is any copy mechanism that could help him to make a copy of his developed house any time he wants to have one.
Prototype design pattern could satisfy developers wish. In this case he can make a copy of his developed house (prototype) and decorate it in different way.

namespace DesignPatterns.Creational.Prototype
{
    /// <summary>
    /// Door class is a class that we are going to make cloneable.
    /// In C# .NET, we inherit ICloneable interface to make our class a cloneable class.
    /// In order to implement the clone() method, either shallow copy or deep copy could be used.
    /// </summary>
    public class Door:ICloneable
    {
        public string DoorColor
        {
            get;
            set;

        }
        public int DoorSize
        {
            get;
            set;
        }
        public string DoorType
        {
            get;
            set;
        }

        public void Display()
        {
            Console.WriteLine("I have {0} {1} ", DoorColor, DoorSize);
        }
        /// <summary>
        ///  Implement the Interface. Create a shallow copy of current object
        /// </summary>
        /// <returns></returns>
        public object Clone()
        {
            return this.MemberwiseClone();
        }

    }

public class Floor :ICloneable
    {
        public string FloorType
        {
            get;
            set;
        }

        public void Display()
        {
            Console.WriteLine("I have {0}  ", FloorType);
        }
        /// <summary>
        ///  Implement the Interface. Create a shallow copy of current object
        /// </summary>
        /// <returns></returns>
        public object Clone()
        {
            return this.MemberwiseClone();
        }
    }
public class Wall: ICloneable
    {
        public int WallHeight
        {
            get;
            set;
        }
        public int WallWidth
        {
            get;
            set;

        }
        public string WallType
        {
            get;
            set;
        }

        public void Display()
        {
            Console.WriteLine("I have {0} {1} {2} ",WallHeight,WallWidth, WallType);
        }
        /// <summary>
        ///  Implement the Interface. Create a shallow copy of current object
        /// </summary>
        /// <returns></returns>
        public object Clone()
        {
            return this.MemberwiseClone();
        }
    }
public class Window:ICloneable
    {
        public string WindowColor
        {
            get;
            set;
        }
       
        public string WindowType
        {
            get;
            set;
        }

        public void Display()
        {
            Console.WriteLine("I have {0} {1}  ",WindowColor,WindowType );
        }
        /// <summary>
        ///  Implement the Interface. Create a shallow copy of current object
        /// </summary>
        /// <returns></returns>
        public object Clone()
        {
            return this.MemberwiseClone();
        }

    }

public class House : ICloneable
    {
        public Floor floor
        {
            get;
            set;
        }
        public Wall wall
        {
            get;
            set;
        }
        public Door door
        {
            get;
            set;
        }
        public Window window
        {
            get;
            set;
        }
        public string HouseName
        {
            get;
            set;
        }


        // default constructor.
        public House()
        {
            floor = new Floor();
            wall = new Wall();
            door = new Door();
            window = new Window();
        }

        // constructor to implement deep copy

        public House(House newhouse)
        {
            floor = newhouse.floor;
            wall = newhouse.wall;
            door = newhouse.door;
            window = newhouse.window;
            HouseName = newhouse.HouseName;
        }

        // Method to show the result
      
        public void Dispaly()
        {

            Console.WriteLine("I am  " + HouseName);
            floor.Display();
            wall.Display();
            door.Display();
            window.Display();

            Console.WriteLine();
        }

       
        //call deep coy to perform clone process
        public object Clone()
        {
            return new House(this);
        }



    }
}// end of namespace

class Program
    {
        static void Main(string[] args)
        {
           

            House house = new House();
            house.HouseName = "SankalpGad";
            house.floor.FloorType = "Glass Floor";
            house.wall.WallHeight = 15;
            house.wall.WallWidth = 5;
            house.wall.WallType = "Glass";
            house.door.DoorColor = "White";
            house.door.DoorSize = 8;
            house.door.DoorType = "Glass";
            house.window.WindowColor = "Black";
            house.window.WindowType = "Glass";

            House copiedHouse = (House)house.Clone();

            Console.WriteLine("Display the House");
            house.Dispaly();

            Console.WriteLine("Display the Copied House");
            copiedHouse.Dispaly();

            copiedHouse.HouseName = "New SankalpGad";
            copiedHouse.floor.FloorType = "Wooden Floor";
            copiedHouse.door.DoorType = "Wooden";

            Console.WriteLine("Display the Copied House after some changes.");
            copiedHouse.Dispaly();


           
        }
}

e.      Singleton Pattern: Singleton pattern is based on the concept of the restricting the instantiation of the class to the one object. Say one object will perform the role of the coordinator between various instances of the application that depend on a common object; we may design an application using a singleton. Usage of Singleton pattern in common in Banking, Finance and Travel base application where single object consist of Network related information. A singleton class may be used to instantiate an object of it, only if that object does not already exist. In case if the object exists the reference to the existing object is given. A single object has one global point of access to it.
In ASP.Net Web Farm is also based on singleton pattern. In web farm several applications resided on the web server. Session state is handled by singleton object in the form of aspnet_state.exe that interacts with aspnet_wp.exe running on each web server. Imagine one of the web server is shutting down, the singleton object still maintain the session state information across all web servers in the web farm.

namespace DesignPatterns.Creational.Singleton
{
    public class Singleton
    {
        private int intNumber;
        // declare the static object of singleton class.
        private static Singleton instance;

        public int Number
        {
            get
            {
                return intNumber;
            }
            set
            {
                intNumber = value;
            }
        }

        /// <summary>
        ///  Portected constructor of the Singleton Class.
        /// </summary>
        protected Singleton()
        {
        }

        /// <summary>
        /// To create the object of Singleton class.
        /// </summary>
        /// <returns></returns>
        public static Singleton Instance()
        {
            // if the object in Null then create a New object else return existing object.
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }

    }
}
class Program
    {
        static void Main(string[] args)
        {
           

Singleton singleobject = Singleton.Instance();
            Singleton singleobject1 = Singleton.Instance();
            if (singleobject == singleobject1)
            {
                Console.WriteLine("Object are same");

            }
            singleobject.Number = 2;

Console.WriteLine("SingleObject Number=" + singleobject.Number.ToString());

            singleobject1.Number = 5;

Console.WriteLine("SingleObject Number=" + singleobject.Number.ToString());

Console.WriteLine("Upated SingleObject Number=" + singleobject.Number.ToString());
           
        }
}

No comments:

Post a Comment