Desgin Pattern - Factory Design pattern





     What is It?

       1.     Factory method pattern falls under Creational Pattern 
       2.    Defines an interface for creating an object
       3.    Lets the classes that implement the interface decide which class to instantiate
       4.    Used to replace class constructors,abstracting the process of object generation,
              so that the type of object instantiated can be determined at run – time.

Where to Use It?
It is tedious when the client needs to specify the class name while creating the objects. So, to resolve this problem, we can use Factory Method design pattern. It provides the client a simple way to create the object.
Example :-
[Download the project for example.]

using System;

namespace TestDemo.FACTORY
{
    
    public interface IFactory
    {
        void Drive(int miles);
    }

    /// <summary>
    /// A 'ConcreteProduct' class
    /// </summary>
    public class Scooter : IFactory
    {
        public void Drive(int miles)
        {
            Console.WriteLine("Drive the Scooter : " + miles.ToString() + "km");
        }
    }

    /// <summary>
    /// A 'ConcreteProduct' class
    /// </summary>
    public class Bike : IFactory
    {
        public void Drive(int miles)
        {
            Console.WriteLine("Drive the Bike : " + miles.ToString() + "km");
        }
    }

    /// <summary>
    /// The Creator Abstract Class
    /// </summary>
    public abstract class VehicleFactory
    {
        public abstract IFactory GetVehicle(string Vehicle);

    }

    /// <summary>
    /// A 'ConcreteCreator' class
    /// </summary>
    public class ConcreteVehicleFactory : VehicleFactory
    {
        public override IFactory GetVehicle(string Vehicle)
        {
            switch (Vehicle)
            {
                case "Scooter":
                    return new Scooter();
                case "Bike":
                    return new Bike();
                default:
                    throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Vehicle));
            }
        }

    }

}

//Class - program.cs

  public class Program
    {
        public static void Main(string[] args)
        {
              FactoryPattern();
        }


        private static void FactoryPattern()
        {
            VehicleFactory factory = new ConcreteVehicleFactory();

            IFactory scooter = factory.GetVehicle("Scooter");
            scooter.Drive(10);

            IFactory bike = factory.GetVehicle("Bike");
            bike.Drive(20);

            Console.ReadKey();
        }
    


    }

Comments

Popular posts from this blog

JWT - Token based authentication