Friday, June 7, 2013

Factory Pattern in c#

We looked the factory design pattern,
    --> which is used to instantiate objects 
    --> based on another data type such as integers. 
    --> Factories can be used to reduce code bloat 
    --> and also make it easier to modify which objects need to be created.
    ==> You can use the Factory type to handle object creation in a uniform and concise way.

class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 4; i++)
            {
                var Position = Factory.Get(i);
                Console.WriteLine("where id={0},position={1}", i, Position.Title);
                Console.ReadKey();
            }
        }
    }
    //==============Factory Class========
    static class Factory
    {
        public static Position Get(int id)
        {
            switch (id)
            { 
                case 0:
                    return new Manager();
                case 1:
                case 2:
                    return new Clerk();
                case 3:
                default:
                    return new Programmer();
            }
        }    
    }

    //=====Abstrct class=======
    abstract class Position
    {
        public abstract string Title { get; }
    }
    class Manager : Position
    {

        public override string Title
        {
            get { return "Manager"; }
        }
    }
    class Clerk : Position
    {
        public override string Title
        {
            get { return "Clerk"; }
        }
    }
    class Programmer : Position
    {
        public override string Title
        {
            get { return "Programmer"; }
        }
    }

No comments:

Post a Comment