Tuesday 12 March 2019

factory method design pattern in C#

 public class FactoryTest
    {
        public static void Test()
        {
            AbstractFactory factory = new ConcreteVehicleFactory();
            IFactory scooter = factory.GetType("a");
            scooter.Do();
            IFactory bike = factory.GetType("Bike");
            bike.Do();
            Console.ReadKey();
        }
    }

    public interface IFactory
    {
        void Do();
    }
    /// <summary>
    /// A 'ConcreteProduct' class
    /// </summary>
    public class Scooter : IFactory
    {
        public void Do()
        {
            Console.WriteLine("Drive the Scooter : ");
        }
    }
    /// <summary>
    /// A 'ConcreteProduct' class
    /// </summary>
    public class Bike : IFactory
    {
        public void Do()
        {
            Console.WriteLine("Drive the Bike : ");
        }
    }
    /// <summary>
    /// The Creator Abstract Class
    /// </summary>
    public abstract class AbstractFactory
    {
        public abstract IFactory GetType(string type);
    }
    /// <summary>
    /// A 'ConcreteCreator' class
    /// </summary>
    public class ConcreteVehicleFactory : AbstractFactory
    {
        public override IFactory GetType(string type)
        {
            switch (type)
            {
                case "A":
                    return new Scooter();
                case "B":
                    return new Bike();
                default:
                    throw new ApplicationException(string.Format("cannot be created", type));
            }
        }
    }

No comments:

Post a Comment