Sunday, 18 February 2018

Factory design pattern

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryDesignPattern
{
    public interface IFactory
    {
        void Drive(int miles);
    }

    public class Scooter : IFactory
    {
        public void Drive(int miles)
        {
            Console.WriteLine("Drive scooter "+ miles + "KM");
        }
    }

    public class Bike : IFactory
    {
        public void Drive(int miles)
        {
            Console.WriteLine("Drive bike " + miles + "KM");
        }
    }

    public abstract class VehicleFactory
    {
      public  abstract IFactory GetVehicle(string vehicleType);
    }

    public class DefaultVehicleFactory : VehicleFactory
    {
        public override IFactory GetVehicle(string vehicleType)
        {
           switch(vehicleType)
           {
                case "Scooter":
                    return new Scooter();
                case "Bike":
                    return new Bike();
                default:
                    throw new ApplicationException(string.Format("This '{0}' cannot be created", vehicleType));
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            DefaultVehicleFactory default1= new DefaultVehicleFactory();
            IFactory scooter = default1.GetVehicle("Scooter");
            scooter.Drive(20);
            IFactory bike = default1.GetVehicle("Bike");
            bike.Drive(50);

            Console.ReadLine();
        }
    }
}



No comments:

Post a Comment