Interview Question Categories

FACTORY DESIGN PATTERN

SIMPLE FACTORY DESIGN PATTERN


namespace Factory_Simple
{
    abstract class Aeroplane
    {
        public String Name { get; protected set; }

        abstract public Aeroplane CreateAeroplane();
    }

    class B747:Aeroplane
    {
        public static bool Register()
        {
            return AeroplaneFactory.Register("B747", new B747());
        }

        public B747()
        {
            Name = "B747";
        }

        public override Aeroplane CreateAeroplane()
        {
            return new B747();
        }
    }

    class A380 : Aeroplane
    {
        public static bool Register()
        {
            return AeroplaneFactory.Register("A380", new A380());
        }

        public A380()
        {
            Name = "A380";
        }

        public override Aeroplane CreateAeroplane()
        {
            return new A380();
        }
    }

    static class AeroplaneFactory
    {
        static Dictionary<String,Aeroplane> Aeroplanes = new Dictionary<string,Aeroplane>();
        public static bool Register(String Name, Aeroplane plane)
        {
            Aeroplanes.Add(Name, plane);
            return true;
        }
        
        public static Aeroplane GetAeroplane(String Name)
        {
            if(Aeroplanes.ContainsKey(Name))
            {
                return Aeroplanes[Name].CreateAeroplane();
            }
            return null;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            A380.Register();
            Console.WriteLine(AeroplaneFactory.GetAeroplane("A380").Name);
        }
    }
}

No comments:

Post a Comment