Monday, August 26, 2013

Implementing Factory design pattern in asp.net using c# | Design Patterns | Example Factory design pattern

hi in this post i will show how to implement the Factory design pattern in asp.net

In Factory design pattern we cannot directly create the object of the class we need to send our requirement to the factory class. This factory class will provide us the required object.

it helps us to create object without exposing the instantiation logic to client.

Example :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ConsoleApplication1
{
    interface color
    {
        string GetCarColor();
    }

    class myFactory
    {
        public color GetObj(int type)
        {
            color interfaceObj = null;
            switch (type)
            {
                case 1:
                    interfaceObj = new car1();
                    break;
                case 2:
                    interfaceObj = new car2();
                    break;
                case 3:
                    interfaceObj = new car3();
                    break;
            }
            return interfaceObj;
        }
    }

    class car1 : color
    {
        public string GetCarColor()
        {
            return "Red color car";
        }

    }
    class car2 : color
    {
        public string GetCarColor()
        {
            return "Blue color car";
        }
    }
    class car3 : color
    {
        public string GetCarColor()
        {
            return "White color car";
        }
    }
}

/////Main Class

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            myFactory obj = new myFactory();
            color c = obj.GetObj(2);
            string s = c.GetCarColor();
            Console.WriteLine(s);
            Console.ReadLine();

        }
    }
}

No comments:

Post a Comment