Monday, February 17, 2014

Design Patterns

The GoF Design Patterns are divided into 3 categories :(B.C.S.) Creational Patterns, Structural Patterns and Behavioral Patterns. I am going to explain each GoF Design Pattern in detail and will show you examples of how to write good C#  code that implement those patterns.
http://www.dotnettricks.com/learn/designpatterns

Creational Patterns

The best way to remember Creational pattern is by remembering ABFPS (Abraham Became First President of States

Structural Patterns

To remember structural pattern best is (ABCDFFP)
  • Adapter Pattern: Match interfaces of classes with different interfaces
  • Bridge Pattern:: Separate implementation and object interfaces
  • Composite: Simple and composite objects tree
  • Decorator: Dynamically add responsibilities to objects
  • Facade: Class that represents subclasses and subsystems
  • Flyweight: Minimize memory usage by sharing as much data as possible with similar objects
  • Proxy: Object that represents another object

Behavioral Patterns

Note :- Just remember Music……. 2 MICS On TV (MMIICCSSOTV).
  • Mediator: Encapsulates and simplifies communication between objects
  • Memento: Undo modifications and restore an object to its initial state
  • Interpreter: Include language elements and evaluate sentences in a given language
  • Iterator: Give sequential access to elements in a collection
  • Chain of Responsibility: Pass requests between command and processing objects within a chain of objects
  • Command: Encapsulate a method call as an object containing all necessary information
  • State: Change object behavior depending on its state
  • Strategy: Encapsulate algorithms within a class and make them interchangeable
  • Observer: Notify dependent objects of state changes
  • Template Method: Define an algorithm skeleton and delegate algorithm steps to subclasses so that they may be overridden
  • Visitor: Add new operations to classes without modifying them
http://www.tutorialspoint.com/design_pattern/design_pattern_quick_guide.htm

Creational Patterns

Singleton PatternEnsure a class has only one instance, and provide a global point of access to it.

Ex:
public class Singleton
{
 private static Singleton _instance;
 private Singleton()
 {
  ...
 }

 public static Singleton GetInstance()
 {
  if (_instance== null)
   _instance= new Singleton();

  return _instance;
 }
 ...
 public void doSomething()
 {
  ... 
 }
}




2

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

Problem

For example we have a scenario where based on user input we need to call particular class methods. I have a customer input screen. He enters his choice whether they want to buy a bike or a car. 
Ex:
/
// Interface//
public interface IChoice
{
    string Buy();
}

//
// Factory Class//
public class FactoryChoice
{
    static public IChoice getChoiceObj(string cChoice)
     {
        IChoice objChoice=null;
        if (cChoice.ToLower() == "car")
        {
            objChoice = new clsCar();
        }
        else if (cChoice.ToLower() == "bike")
        {
            objChoice = new clsBike();
        }
        else
        {
            objChoice = new InvalidChoice();
        }
        return objChoice;
    }
}
 
//Business classes//Carpublic class clsBike:IChoice
{
    #region IChoice Members
 
    public string Buy()
    {
        return ("You choose Bike");
    }
 
    #endregion
}
 
//Bikepublic class clsCar:IChoice
{
 
    #region IChoice Members
 
    public string Buy()
    {
        return ("You choose Car");
    }
 
    #endregion
}
From the client class call the factory class object and it will return the interface object. Through the interface object we will call the respective method.
//Client classIChoice objInvoice;
objInvoice = FactoryClass.FactoryChoice.getChoiceObj(txtChoice.Text.Trim());
MessageBox.Show(objInvoice.Buy());
In future if we need to add a new vehicle then there is no need to change the client class, simply return that object using the factory class.

Advantages

Suppose we want to add a decoupled structure and don’t want to disturb the client environment again and again, this pattern is very useful. The factory class will take all the burden of object creations.
 

Proxy Design Pattern

Definition

Provide a surrogate or placeholder for another object to control access to it. 

   public interface Subject
    {
       void PerformAction();
    }    
    public class RealSubject : Subject
    {
    public void PerformAction()
    {
        Console.WriteLine("RealSubject action performed.");
    }
    }    
    public class Proxy : Subject
    {
    private RealSubject _realSubject;    
    public void PerformAction()
    {
    if (_realSubject == null)
    _realSubject = new RealSubject();    
    _realSubject.PerformAction();
    }
    }

Decorator Pattern


Decorator pattern is used to add new functionality to an existing object without changing its structure.

class DecoratorPattern
    {
        private interface IPizza
        {
            int GetPrice();
        }
 
        private class Pizza : IPizza
        {
            public int GetPrice()
            {
                return 10;
            }
        }
 
        //Decorator 1
        private class PizzaWithCheese : IPizza
        {
            private IPizza _pizza;
            private int _priceofCheese;
 
            public PizzaWithCheese(IPizza pizza, int priceofCheese)
            {
                _pizza = pizza;
                _priceofCheese = priceofCheese;
            }
 
            public int GetPrice()
            {
                //get price of the base pizza and add price of cheese to it
                return _pizza.GetPrice() + _priceofCheese;
            }
        }
 
        //Decorator 2
        private class PizzaWithChicken : IPizza
        {
            private IPizza _pizza;
            private int _priceofChicken;
 
            public PizzaWithChicken(IPizza pizza, int priceofChicken)
            {
                _pizza = pizza;
                _priceofChicken = priceofChicken;
            }
 
            public int GetPrice()
            {
                //get price of the base pizza and add price of chicken to it
                return _pizza.GetPrice() + _priceofChicken;
            }
        }
 
 
        public static void Test()
        {           
            var pizzaWithCheese = new PizzaWithCheese(new Pizza(), 5);
            var pizzaWithChicken = new PizzaWithChicken(new Pizza(), 6);
 
            //pizza with chicken and cheese is easy to build now.
            //we can keep decotaring the base pizza with as many decorators as necessary at runtime
            var pizzaWithChickenAndCheese = new PizzaWithChicken(pizzaWithCheese, 6);
 
            Console.WriteLine("Total for cheese pizza: " + pizzaWithCheese.GetPrice());
            Console.WriteLine("Total for chicken pizza: " + pizzaWithChicken.GetPrice());
            Console.WriteLine("Total for cheese + chicken pizza: " + pizzaWithChickenAndCheese.GetPrice());
        }
    }

Factory Method:

http://dotnetfreakblog.wordpress.com/2013/03/02/factory-design-pattern-in-c/


http://www.newguid.net/vs2008-vs2010/2010/design-patternsc-basic-example-strategy-pattern/
http://dotnetfreakblog.wordpress.com/2013/11/10/strategy-design-pattern-using-c/
http://www.blackwasp.co.uk/Strategy.aspx

Adapter Pattern

http://www.c-sharpcorner.com/UploadFile/40e97e/adapter-pattern-in-C-Sharp/
https://csharpdesignpatterns.codeplex.com/wikipage?title=Adapter%20Pattern&referringTitle=Home
Interviewquestion
http://interviewquestion.wordpress.com/design-patterns/
http://computerauthor.blogspot.in/2011/03/design-pattern-interview-questions.html
http://dotnetinterviews.com/Design-Patterns-Questions-Answers.aspx

Template Method
http://www.codeproject.com/Articles/482196/Understanding-and-Implementing-Template-Method-Des
http://sourcemaking.com/design_patterns/template_method/c-sharp-dot-net
Pattern in Bangla 
http://hasin.me/2014/05/14/singleton-design-pattern/

1 comment:

  1. Bro! You have told me before to study & culture various design principle as well as respective patterns... But I ignored then recently
    for job switching purpose I realized how fool am I.Many many respect to you and all the seniors because Yes "Experience" has a concrete value in every walk of life... :)

    ReplyDelete