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

Friday, 13 May 2011

Delegates and Events

Delegates

Delegate is pointer to function. In other way we can say that delegate holds the reference of the function. Instead of calling the function we calling the delegate. Signature of the delegate and signature function should be same. In below example we declare delegate which is not taking any parameter and not returning any value. After understanding delegate I am listing benefits of delegate.

Code Example

namespace BasicDelegate
{

    // Declaration
    public delegate void MyDelegate();


    class DelegateExample
    {
        public static void MyFunction()
        {
            Console.WriteLine("I was called by delegate ...");
        }


        static void Main(string[] args)
        {
            MyDelegate myDelegate = new MyDelegate(MyFunction);
            myDelegate();
            Console.ReadLine();

        }
    }
}


Events

The basic of the event is publisher and subscriber.  Publishers object publish event and any number of object can be subscribe to publisher object. To declare event first we have to declare a delegate. By using delegate event should be declared. In below example we have publisher class which is publishing the event and subscriber class is Program.

Code Example

Main Method
class Program
    {
        //This is simple method which will write into console
        static void Logger(string s)
        {
            Console.WriteLine(s);
        }

        static void Main(string[] args)
        {
            FileLoggerClass fl = new FileLoggerClass("process.log");
            PublisherClass publisherClass = new PublisherClass();

            // Subscribe the Functions Logger and fl.Logger
            publisherClass.Log += new PublisherClass.LogHandler(Logger);
            publisherClass.Log += new PublisherClass.LogHandler(fl.LoggerMethod);

            // The Event will now be triggered in the Process() Method
            publisherClass.Process();

            fl.Close();

        }
    }


Publisher Class
class PublisherClass
    {
        public delegate void LogHandler(string message);
        // Define an Event based on the above Delegate
        public event LogHandler Log;
        // Instead of having the Process() function take a delegate
        // as a parameter, we've declared a Log event. Call the Event,
        // using the OnXXXX Method, where XXXX is the name of the Event.
        public void Process()
        {
            OnLog("Process() begin");
            OnLog("Process() end");
        }
        // By Default, create an OnXXXX Method, to call the Event
        protected void OnLog(string message)
        {
            if (Log != null)
            {
                Log(message);
            }
        }
    }

Simple File logger class

class FileLoggerClass
    {
        FileStream fileStream;
        StreamWriter streamWriter;

        // Constructor
        public FileLoggerClass(string filename)
        {
            fileStream = new FileStream(filename, FileMode.Create);
            streamWriter = new StreamWriter(fileStream);
        }

        // Member Function which is used in the Delegate
        public void LoggerMethod(string s)
        {
            streamWriter.WriteLine(s);
        }

        public void Close()
        {
            streamWriter.Close();
            fileStream.Close();
        }

    }

Saturday, 7 May 2011

Design Principles

1. Open Close Principle
Software entities like classes, modules and functions should be open for extension but closed for modifications.

2. Dependency Inversion
High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend on details. Details should depend on abstractions
3. Interface Segregation
Clients should not be forced to depend upon interfaces that they don't use.

4. Single Responsibility
A class should have only one reason to change.

Composition and Aggregation

Composition

1. Compostion is 'Part of' Relation.
2. The life time of the object managed by main class. If main class
destroyed composited object also destroyed.
3. In UML diagram composition shows with filled diagram.

in below example if Car object destroyed Engine object also destroyed.



Aggregation

Agregation gives 'has a' relationship. Even if main objecte destroyed aggregated object does not destroyed.
If you take Customer class and Address Class. We can say that customer has address we dont say Address is part of the customer. Aggregation show in UML diagram with unfilled diamond.

Monday, 2 May 2011

Reflection in .NET

Reflection - The process of getting the metadata from modules/assemblies. When .NET code is compiled, metadata about the types defined in the modules is produced. These modules are in turn packaged as assemblied. The process of accessing this metadata in called Reflection.
The namespace System.Reflection contains classes that can be used for interrogating the types for a module/assembly. We use reflection for examining data type sizes for marshalling across process & machine boundaries.

.NET Framework's Reflection API allows you to fetch type (assembly) information at runtime programmatically. We can also achieve late binding by using .NET Reflection. At runtime, the Reflection mechanism uses the PE file to read information about the assembly. Reflection enables you to use code that is not available at compile time. .NET Reflection allows an application to collect information about itself and also to manipulate on itself. It can be used effectively to find all types in an assembly and/or dynamically invoke methods in an assembly. This includes information about the type, properties, methods, and events of an object. With Reflection, we can dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. We can also access attribute information using Reflection.

Assembly contain the modules, modules contain the types and type contain members. You can use the reflection to create the instance of the types dynamically. You can invoke the type's method dynamically and can access the fields information.

List of classes which we using in reflection:
  1. Assemly
  2. Module
  3. ConstructorInfo
  4. MethodInfo
  5. FieldInfo
  6. EventInfo
  7. PropertyInfo
  8. ParameterInfo

Saturday, 30 April 2011

IComparable and IComparer Interface in .NET

IComparable

The IComparable allows us to create a type-specific comparison method. If we implement the IComparable interface, we need to implement the IComparable’s member: CompareTo method. We usually compare if two instances of that class are equal using IComparable.

IComparer
The IComparer also allows us to create a type-specific comparison method. If we implement the IComparer interface, we need to implement the IComparer’s member: Compare method. We usually customize the sort order of a collection using IComparer.