Showing posts with label Design Pattern. Show all posts
Showing posts with label Design Pattern. Show all posts

Tuesday, 7 June 2011

Factory Method Design Pattern


The Factory Method pattern is way of creating objects, but letting subclasses decided exactly which class to instantiate. All factory method encapsulates creation of object. Creator class creates the object of the product based on values supplied by the client.
In this example participant are:
Product Interface and product classes.
IColorProduct
RedColore
GreenColor
BlueColor

Creator Class
ColorCreator
UML Diagram 
FactoryDesignPattern
 
Code Explanation
I created IColorProduct Interface. This interface implemented by 3 classes RedColor, GreenColor and BlueColor. Based on passed values by client, Creator class (ColorCreator) creates different classes.
Code Sample
   1: interface IColorProduct
   2:     {
   3:         Color GetColor();
   4:     }
   5:  
   6:     public class RedColor : IColorProduct
   7:     {
   8:  
   9:         public Color GetColor()
  10:         {
  11:             return Color.Red;
  12:         }
  13:     }
  14:  
  15:     public class GreenColor : IColorProduct
  16:     {
  17:         public Color GetColor()
  18:         {
  19:             return Color.Green;
  20:         }
  21:     }
  22:     public class BlueColor : IColorProduct
  23:     {
  24:         public Color GetColor()
  25:         {
  26:             return Color.Blue;
  27:         }
  28:     }
  29:  
  30: class ColorCreator
  31:    {
  32:        IColorProduct colorProduct;
  33:        public Color  GetColorFactory(string  ColorCode)
  34:        {
  35:            
  36:  
  37:            switch (ColorCode)
  38:            {
  39:                case "rdoBlue":
  40:                    colorProduct = new BlueColor();
  41:                    break;
  42:                case "rdoRed":
  43:                    colorProduct = new RedColor();
  44:                    break;
  45:                case "rdoGreen":
  46:                    colorProduct = new GreenColor();
  47:                    break;
  48:                default:
  49:                    colorProduct = new GreenColor();
  50:                    break;
  51:  
  52:            }
  53:            return colorProduct.GetColor(); 
  54:        }
  55:    }
  56: private void rdo_CheckedChanged(object sender, EventArgs e)
  57:         {
  58:             RadioButton radioButton = (RadioButton)sender;
  59:             string strSelected="";
  60:             if(radioButton.Checked==true)
  61:                  strSelected = radioButton.Name;
  62:             ColorCreator creator = new ColorCreator();
  63:             panel1.BackColor = creator.GetColorFactory(strSelected);
  64:  
  65:         }
  66: //For three radio button only one event handler
  67: this.rdoBlue.CheckedChanged += new System.EventHandler(this.rdo_CheckedChanged);
  68: this.rdoRed.CheckedChanged += new System.EventHandler(this.rdo_CheckedChanged);
  69: this.rdoGreen.CheckedChanged += new System.EventHandler(this.rdo_CheckedChanged);

Achievement

  1. By using factory method we centralized creation of the objects in one location.
  2. Client who ever using factory method responsibility is only passing values. Based on values different color objects are returning. Client no need to know internal logic of creation of object.
  3. In future if we add new color class there is no impact on client code.
  4. Hinding object creation logic inside Factory class.

 


Saturday, 21 May 2011

Design Patterns


I am starting to write articles on design patterns. We have 3 types of design patterns as per GoF. There are plenty of design patterns available but 23 standard pattern I am going to cover in my article. Design patterns are Solutions to commonly occurring design problem. Someone has already faced the problem and come up with good and elegant solution. The same pattern you have to use. Design Pattern divided into 3 categories.
  1. Creational
  2. Behavioral
  3. Structural
    1. Creational
      Concerned about ways to create new objects.  
    2. Behavioral
      Concerned about ways in which objects interacted  
    3. Strucural
      Concerned about the composition of objects and classes
Creational Patterns
SingletonTo Create a sole instance of a class
PrototypeTo create object by cloning existing object.
BuilderBuild an object from existing representation
Factory MethodDefer instantiation to subclass
Abstract FactoryProvides interface to create families of objects without specifying the concrete classes of the objects
Structural Patterns
AdapterConvert an instance to another
CompositeComposite objects in a tree structure
DecoratorAttach additional responsibilities dynamically
ProxyProvide a surrogate or placeholder for another object
FaçadeProvide a unified instance to a set of instances in sub system
BridgeDecouple abstraction from implementation. Let them vary and independent.
FlyweightA fine-grained instance user for efficient sharing
Behavioral Pattern
Chain of Resp.Delegates commands to a chain of processing objects.
CommandCreates objects which encapsulate actions and parameters.
InterpreterImplements a specialized language.
IteratorAccesses the elements of an object sequentially without exposing its underlying representation.
MediatorAllows loose coupling between classes by being the only class that has detailed knowledge of their methods.
MementoProvides the ability to restore an object to its previous state (undo).
ObserverPublish/subscribe pattern which allows a number of observer objects to see an event.
StateAllows an object to alter its behavior when it's internal state changes.
StrategyAllows one of a family of algorithms to be selected on-the-fly at runtime.
Template MethodDefines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.
VisitorSeparates an algorithm from an object structure by moving the hierarchy of methods into one object.

Reference Books

C# 3.0 Design Patterns
Design Patterns in C#

C# 3.0 Design Patterns
Agile Principles, Patterns, and Practices in C#
Pro .NET 4 Parallel Programming in C# (Expert's Voice in .NET)
C# Design Patterns: A Tutorial