Tuesday, 2 June 2015

Factory Design Pattern - C#

Design patterns are general reusable solutions to common problems that occurred in software designing. There are broadly 3 categories of design patterns, i.e., Creational, Behavioral and Structural.

Now, Factory Design Pattern falls under the category of creational design pattern.
Factory design pattern is one of the common design pattern  in software project. Let’s understand the basic of Factory design patern.


         It deals with the problem of creating objects without specifying the exact class of object that will be created. The essence of this pattern is to "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. 

Definition:Factory it's such a Design Pattern which defines an interface for creating an object, but lets the classes that implement the interface decide which class to instantiate. Factory Pattern lets a class postpone instantiation to sub-classes.

Factory design pattern is one of the common design pattern  in software project. Let’s understand the basic of Factory design pattern.


See the Simplest Example Code Factory Pattern Example Code in C#

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:

Product
This is an interface for creating the objects.

ConcreteProduct
This is a class which implements the Product interface.

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

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:

IFactory - Interface
Scooter & Bike - Concreate Product classes
VehicleFactory - Creator
ConcreteVehicleFactory - Concreate Creator

namespace FactoryDesignPattern
{
    /// <summary>
    /// The 'Product' interface
    /// </summary>
    public interface IFactory
    {
        void Drive(int miles);
    }

    /// <summary>
    /// A 'Concrete Scooter' class
    /// </summary>
    public class Scooter : IFactory
    {
        public void Drive(int miles)
        {
            Console.WriteLine("Drive the Scooter : " + miles.ToString() + "km");
        }
    }

    /// <summary>
    /// A 'Concrete Bike' 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));
            }
        }
    }


   public 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.


Some more usefull links are: link1link2

0 comments:

Post a Comment

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (9) Web Service (1) XMl (1)