Thursday, 26 December 2013

.NET Design Patterns


http://www.tutorialspoint.com/design_pattern/observer_pattern.htm 

http://www.codeguru.com/csharp/.net/net_asp/mvc/using-the-repository-pattern-with-asp.net-mvc-and-entity-framework.htm 

http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application


http://dotnetcodr.com/2013/05/09/design-patterns-and-practices-in-net-the-singleton-pattern/

.NET Design Patterns

Design patterns are solutions to software design problems you find again and again in real-world application development. Patterns are about reusable designs and interactions of objects..

They are categorized in three groups: Creational, Structural, and Behavioral

  Creational Patterns
  Abstract Factory   Creates an instance of several families of classes
  Builder   Separates object construction from its representation
  Factory Method   Creates an instance of several derived classes
  Prototype   A fully initialized instance to be copied or cloned
  Singleton   A class of which only a single instance can exist

  Structural Patterns
  Adapter   Match interfaces of different classes
  Bridge   Separates an object’s interface from its implementation
  Composite   A tree structure of simple and composite objects
  Decorator   Add responsibilities to objects dynamically
  Facade   A single class that represents an entire subsystem
  Flyweight   A fine-grained instance used for efficient sharing
  Proxy   An object representing another object

  Behavioral Patterns
  Chain of Resp.   A way of passing a request between a chain of objects
  Command   Encapsulate a command request as an object
  Interpreter   A way to include language elements in a program
  Iterator   Sequentially access the elements of a collection
  Mediator   Defines simplified communication between classes
  Memento   Capture and restore an object's internal state
  Observer   A way of notifying change to a number of classes
  State   Alter an object's behavior when its state changes
  Strategy   Encapsulates an algorithm inside a class
  Template Method   Defer the exact steps of an algorithm to a subclass
  Visitor   Defines a new operation to a class without change

Proxy Design Pattern

Proxy Design Pattern

Proxy pattern falls under Structural Pattern of Gang of Four (GOF) Design Patterns in .Net. The proxy design pattern is used to provide a surrogate object, which references to other object. In this article, I would like share what is proxy pattern and how is it work?

What is Proxy Pattern

The proxy design pattern is used to provide a surrogate object, which references to other object.
Proxy pattern involves a class, called proxy class, which represents functionality of another class.

Proxy Pattern - UML Diagram & Implementation

The UML class diagram for the implementation of the proxy design pattern is given below:

 
 The classes and/or objects participating in this pattern are:
  • Proxy   (MathProxy)
    • maintains a reference that lets the proxy access the real subject. Proxy may refer to a Subject if the RealSubject and Subject interfaces are the same.
    • provides an interface identical to Subject's so that a proxy can be substituted for for the real subject.
    • controls access to the real subject and may be responsible for creating and deleting it.
    • other responsibilites depend on the kind of proxy:
      • remote proxies are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.
      • virtual proxies may cache additional information about the real subject so that they can postpone accessing it. For example, the ImageProxy from the Motivation caches the real images's extent.
      • protection proxies check that the caller has the access permissions required to perform a request.
  • Subject   (IMath)
    • defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected.
  • RealSubject   (Math)
    • defines the real object that the proxy represents. 

Who is what?

The classes, interfaces and objects in the above class diagram can be identified as follows:
  1. IClient- Subject Interface.
  2. RealClient - RealSubject Class.
  3. ProxyClient - Proxy Class.

C# - Sample Code

using System;

namespace DoFactory.GangOfFour.Proxy.RealWorld
{
  /// <summary>
  /// MainApp startup class for Real-World
  /// Proxy Design Pattern.
  /// </summary>
  class MainApp
  {
    /// <summary>
    /// Entry point into console application.
    /// </summary>
    static void Main()
    {
      // Create math proxy
      MathProxy proxy = new MathProxy();

      // Do the math
      Console.WriteLine("4 + 2 = " + proxy.Add(4, 2));
      Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
      Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2));
      Console.WriteLine("4 / 2 = " + proxy.Div(4, 2));

      // Wait for user
      Console.ReadKey();
    }
  }

  /// <summary>
  /// The 'Subject interface
  /// </summary>
  public interface IMath
  {
    double Add(double x, double y);
    double Sub(double x, double y);
    double Mul(double x, double y);
    double Div(double x, double y);
  }

  /// <summary>
  /// The 'RealSubject' class
  /// </summary>
  class Math : IMath
  {
    public double Add(double x, double y) { return x + y; }
    public double Sub(double x, double y) { return x - y; }
    public double Mul(double x, double y) { return x * y; }
    public double Div(double x, double y) { return x / y; }
  }

  /// <summary>
  /// The 'Proxy Object' class
  /// </summary>
  class MathProxy : IMath
  {
    private Math _math = new Math();

    public double Add(double x, double y)
    {
      return _math.Add(x, y);
    }
    public double Sub(double x, double y)
    {
      return _math.Sub(x, y);
    }
    public double Mul(double x, double y)
    {
      return _math.Mul(x, y);
    }
    public double Div(double x, double y)
    {
      return _math.Div(x, y);
    }
  }
}

Output
4 + 2 = 6
4 - 2 = 2
4 * 2 = 8
4 / 2 = 2
 
There are various kinds of proxies, some of them are as follows:
  1. Virtual proxies : Hand over the creation of an object to another object
  2. Authentication proxies : Checks the access permissions for a request
  3. Remote proxies : Encodes requests and send them across a network
  4. Smart proxies : Change requests before sending them across a network

When to use it?

  1. Objects need to be created on demand means when their operations are requested.
  2. Access control for the original object is required.
  3. Allow to access a remote object by using a local object(it will refer to a remote object).

 

 

Singleton Design Pattern

Singleton Design Pattern

http://www.oodesign.com/singleton-pattern.html
Singleton pattern falls under Creational Pattern of Gang of Four (GOF) Design Patterns in .Net. It is pattern is one of the simplest design patterns. This pattern ensures that a class has only one instance. In this article, I would like share what is Singleton pattern and how is it work?

What is Singleton Pattern?

Singleton pattern is one of the simplest design patterns. This pattern ensures that a class has only one instance and provides a global point of access to it.

Singleton Pattern - UML Diagram & Implementation

The UML class diagram for the implementation of the Singleton design pattern is given below:
The classes, and objects in the above UML class diagram are as follows:
  1. Singleton

    This is a class which is responsible for creating and maintaining its own unique instance.

C# - Implementation Code

//eager initialization of singleton
public class Singleton
{
    private static Singleton instance = new Singleton();
    private Singleton() { }
 
    public static Singleton GetInstance
    {
        get
        {
            return instance;
        }
    }
}
 
////lazy initialization of singleton
public class Singleton
{
    private static Singleton instance = null;
    private Singleton() { }
 
    public static Singleton GetInstance
    {
        get
        {
            if (instance == null)
            instance = new Singleton();
            return instance;
        }
    }
}
 
////Thread-safe (Double-checked Locking) initialization of singleton
public class Singleton
{
    private static Singleton instance = null;
    private Singleton() { }
    private static object lockThis = new object();
 
    public static Singleton GetInstance
    {
        get
        {
            lock (lockThis)
            {
                if (instance == null)
                instance = new Singleton();
                return instance;
            }
        }
    }
}

Singleton Pattern - Example

Who is what?

The classes and objects in the above class diagram can be identified as follows:
  1. Singleton - Singleton class

C# - Sample Code

/// <summary>
/// The 'Singleton' class
/// </summary>
public class Singleton
{
    // .NET guarantees thread safety for static initialization
    private static Singleton instance = null;
    private string Name{get;set;}
    private string IP{get;set;}
    private Singleton()
    {
         //To DO: Remove below line
         Console.WriteLine("Singleton Intance");
 
         Name = "Server1";
         IP = "192.168.1.23";
    }
    // Lock synchronization object
    private static object syncLock = new object();
 
    public static Singleton Instance
    {
        get
        {
            // Support multithreaded applications through
            // 'Double checked locking' pattern which (once
            // the instance exists) avoids locking each
            // time the method is invoked
            lock (syncLock)
            {
                if (Singleton.instance == null)
                Singleton.instance = new Singleton();
                return Singleton.instance;
            }
        }
    }
 
    public void Show()
    {
        Console.WriteLine("Server Information is : Name={0} & IP={1}", IP, Name);
    }
 
}
 
/// <summary>
/// Singleton Pattern Demo
/// </summary>
/// 
class Program
{
    static void Main(string[] args)
    {
        Singleton.Instance.Show();
        Singleton.Instance.Show();
        Console.ReadKey();
    }
}

Singleton Pattern Demo - Output

When to use it?

  1. Exactly one instance of a class is required.
  2. Controlled access to a single object is necessary.

Abstract Factory Pattern

Abstract Factory Design Pattern

Abstract Factory method pattern falls under Creational Pattern of Gang of Four (GOF) Design Patterns in .Net. It is used to create a set of related objects, or dependent objects. Internally, Abstract Factory use Factory design pattern for creating objects. It may also use Builder design pattern and prototype design pattern for creating objects. It completely depends upon your implementation for creating objects. In this article, I would like share what is abstract factory pattern and how is it work?

What is Abstract Factory Pattern?

Abstract Factory patterns acts a super-factory which creates other factories. This pattern is also called as Factory of factories. In Abstract Factory pattern an interface is responsible for creating a set of related objects, or dependent objects without specifying their concrete classes.

Abstract Factory Pattern - UML Diagram & Implementation

 

The UML class diagram for the implementation of the abstract factory design pattern is given below:
The classes, interfaces and objects in the above UML class diagram are as follows:
  1. AbstractFactory

    This is an interface which is used to create abstract product
  2. ConcreteFactory

    This is a class which implements the AbstractFactory interface to create concrete products.
  3. AbstractProduct

    This is an interface which declares a type of product.
  4. ConcreteProduct

    This is a class which implements the AbstractProduct interface to create product.
  5. Client

    This is a class which use AbstractFactory and AbstractProduct interfaces to create a family of related objects.

C# - Implementation Code

public interface AbstractProductA { }
 
public class ProductA1 : AbstractProductA { }
 
public class ProductA2 : AbstractProductA { }
 
public interface AbstractProductB { }
 
public class ProductB1 : AbstractProductB { }
 
public class ProductB2 : AbstractProductB { }
 
public interface AbstractFactory
{
    AbstractProductA CreateProductA();
 
    AbstractProductB CreateProductB();
}
 
public class ConcreteFactoryA : AbstractFactory
{
    public AbstractProductA CreateProductA()
    {
        return new ProductA1();
    }
 
    public AbstractProductB CreateProductB()
    {
        return new ProductB1();
    }
}
 
public class ConcreteFactoryB : AbstractFactory
{
    public AbstractProductA CreateProductA()
    {
        return new ProductA2();
    }
 
    public AbstractProductB CreateProductB()
    {
        return new ProductB2();
    }
}
 

public class Client
{
    private AbstractProductA _productA;
    private AbstractProductB _productB;
 
    public Client(AbstractFactory factory)
    {
        _productA = factory.CreateProductA();
        _productB = factory.CreateProductB();
    }
}

Abstract Factory Pattern - Example

Who is what?

The classes, interfaces and objects in the above class diagram can be identified as follows:
  1. VehicleFactory - AbstractFactory interface
  2. HondaFactory & HeroFactory- Concrete Factories
  3. Bike & Scooter - AbstractProduct interface
  4. Regular Bike, Sports Bike, Regular Scooter & Scooty - Concreate Products
  5. VehicleClient - Client

C# - Sample Code

 
/// <summary>
/// The 'AbstractProductA' interface
/// </summary>
interface Bike
{
 string Name();
}
 
/// <summary>
/// The 'AbstractProductB' interface
/// </summary>
interface Scooter
{
 string Name();
}
 
/// <summary>
/// The 'ProductA1' class
/// </summary>
class RegularBike : Bike
{
    public string Name()
    {
        return "Regular Bike- Name";
    }
}
 
/// <summary>
/// The 'ProductA2' class
/// </summary>
class SportsBike : Bike
{
    public string Name()
    {
        return "Sports Bike- Name";
    }
}
 
/// <summary>
/// The 'ProductB1' class
/// </summary>
class RegularScooter : Scooter
{
    public string Name()
    {
        return "Regular Scooter- Name";
    }
}
 
/// <summary>
/// The 'ProductB2' class
/// </summary>
class Scooty : Scooter
{
    public string Name()
    {
        return "Scooty- Name";
    }
} 
 
 /// <summary>
/// The 'AbstractFactory' interface. 
/// </summary>
interface VehicleFactory
{
   Bike GetBike(string Bike);
   Scooter GetScooter(string Scooter);
}
 
/// <summary>
/// The 'ConcreteFactory1' class.
/// </summary>
class HondaFactory : VehicleFactory
{
   public Bike GetBike(string Bike)
   {
      switch (Bike)
      {
         case "Sports":
         return new SportsBike();
         case "Regular":
         return new RegularBike();
         default:
         throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Bike));
      }
 
   }
 
   public Scooter GetScooter(string Scooter)
   {
      switch (Scooter)
      {
         case "Sports":
         return new Scooty();
         case "Regular":
         return new RegularScooter();
         default:
         throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Scooter));
      }
 
   }
}
 
/// <summary>
/// The 'ConcreteFactory2' class.
/// </summary>
class HeroFactory : VehicleFactory
{
   public Bike GetBike(string Bike)
   {
      switch (Bike)
      {
          case "Sports":
          return new SportsBike();
          case "Regular":
          return new RegularBike();
          default:
          throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Bike));
      }
   }
 
   public Scooter GetScooter(string Scooter)
   {
      switch (Scooter)
      {
          case "Sports":
          return new Scooty();
          case "Regular":
          return new RegularScooter();
          default:
          throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Scooter));
       }
 
    }
}
 

 
/// <summary>
/// The 'Client' class 
/// </summary>
class VehicleClient
{
    Bike bike;
    Scooter scooter;
 
    public VehicleClient(VehicleFactory factory, string type)
    {
         bike = factory.GetBike(type);
         scooter = factory.GetScooter(type);
    }
 
    public string GetBikeName()
    {
         return bike.Name();
    }
 
    public string GetScooterName()
    {
         return scooter.Name();
    }
 
}
 
/// <summary>
/// Abstract Factory Pattern Demo
/// </summary>
class Program
{
    static void Main(string[] args)
    {
        VehicleFactory honda = new HondaFactory();
        VehicleClient hondaclient = new VehicleClient(honda, "Regular");
 
        Console.WriteLine("******* Honda **********");
        Console.WriteLine(hondaclient.GetBikeName());
        Console.WriteLine(hondaclient.GetScooterName());
 
        hondaclient = new VehicleClient(honda, "Sports");
        Console.WriteLine(hondaclient.GetBikeName());
        Console.WriteLine(hondaclient.GetScooterName());
 
        VehicleFactory hero = new HeroFactory();
        VehicleClient heroclient = new VehicleClient(hero, "Regular");
 
        Console.WriteLine("******* Hero **********");
        Console.WriteLine(heroclient.GetBikeName());
        Console.WriteLine(heroclient.GetScooterName());
 
        heroclient = new VehicleClient(hero, "Sports");
        Console.WriteLine(heroclient.GetBikeName());
        Console.WriteLine(heroclient.GetScooterName());
 
        Console.ReadKey();
    }
}

Abstract Factory Pattern Demo - Output

When to use it?

  1. Create a set of related objects, or dependent objects which must be used together.
  2. System should be configured to work with multiple families of products.
  3. The creation of objects should be independent from the utilizing system.
  4. Concrete classes should be decoupled from clients.

Note:

  1. Internally, Abstract Factory use Factory design pattern for creating objects. But it can also use Builder design pattern and prototype design pattern for creating objects. It completely depends upon your implementation for creating objects.
  2. Abstract Factory can be used as an alternative to Facade to hide platform-specific classes.
  3. When Abstract Factory, Builder, and Prototype define a factory for creating the objects, we should consider the following points :
    1. Abstract Factory use the factory for creating objects of several classes.
    2. Builder use the factory for creating a complex object by using simple objects and a step by step approach.
    3. Prototype use the factory for building a object by copying an existing object.

 

Factory Pattern

Factory Method Design Pattern

 

Factory method pattern falls under Creational Pattern of Gang of Four (GOF) Design Patterns in .Net. It is used to create objects. People usually use this pattern as the standard way to create objects. In this article, I would like share what is factory pattern and how is it work?

What is Factory Method Pattern?

In Factory pattern, we create object without exposing the creation logic. In this pattern, an interface is used for creating an object, but let subclass decide which class to instantiate. The creation of object is done when it is required. The Factory method allows a class later instantiation to subclasses.

Factory Method Pattern - UML Diagram & Implementation

The UML class diagram for the implementation of the factory method design pattern is given below:
The classes, interfaces and objects in the above UML class diagram are as follows:
  1. Product

    This is an interface for creating the objects.
  2. ConcreteProduct

    This is a class which implements the Product interface.
  3. Creator

    This is an abstract class and declares the factory method, which returns an object of type Product.
  4. ConcreteCreator

    This is a class which implements the Creator class and overrides the factory method to return an instance of a ConcreteProduct.

C# - Implementation Code

interface Product {
}

class ConcreteProductA : Product
{
}
class ConcreteProductB : Product
{
}
 
abstract class Creator
{
      public abstract Product FactoryMethod(string type);
}
 
class ConcreteCreator : Creator
{
      public override Product FactoryMethod(string type)
      {
           switch (type)
           {
                 case "A": return new ConcreteProductA();
                 case "B": return new ConcreteProductB();
                 default: throw new ArgumentException("Invalid type", "type");
           }
      }
}

Factory Method Pattern - Example

Who is what?

The classes, interfaces and objects in the above class diagram can be identified as follows:
  1. IFactory - Interface
  2. Scooter & Bike - Concreate Product classes
  3. VehicleFactory - Creator
  4. ConcreteVehicleFactory - Concreate Creator

C# - Sample Code

using System; namespace Factory { /// <summary> /// The 'Product' interface /// </summary> public interface IFactory { void Drive(int miles); }   /// <summary> /// A 'ConcreteProduct' class /// </summary> public class Scooter : IFactory { public void Drive(int miles) { Console.WriteLine("Drive the Scooter : " + miles.ToString() + "km"); } }   /// <summary> /// A 'ConcreteProduct' class /// </summary> public class Bike : IFactory { public void Drive(int miles) { Console.WriteLine("Drive the Bike : " + miles.ToString() + "km"); } }   /// <summary> /// The Creator Abstract Class /// </summary> public abstract class VehicleFactory { public abstract IFactory GetVehicle(string Vehicle);   }   /// <summary> /// A 'ConcreteCreator' class /// </summary> public class ConcreteVehicleFactory : VehicleFactory { public override IFactory GetVehicle(string Vehicle) { switch (Vehicle) { case "Scooter": return new Scooter(); case "Bike": return new Bike(); default: throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Vehicle)); } }   } /// <summary> /// Factory Pattern Demo /// </summary> class Program { static void Main(string[] args) { VehicleFactory factory = new ConcreteVehicleFactory();   IFactory scooter = factory.GetVehicle("Scooter"); scooter.Drive(10);   IFactory bike = factory.GetVehicle("Bike"); bike.Drive(20);   Console.ReadKey();   } } }

Factory Pattern Demo - Output

When to use it?

  1. Subclasses figure out what objects should be created.
  2. Parent class allows later instantiation to subclasses means the creation of object is done when it is required.
  3. The process of objects creation is required to centralize within the application.
  4. A class (creator) will not know what classes it will be required to create.