Factory Design Pattern


Factory Design Pattern

In Factory pattern, we create object without exposing the creation logic. In this pattern, an interface is used for creating an object, but let subclass decide which class to instantiate. The creation of object is done when it is required. The Factory method allows a class later instantiation to subclasses.
Template:

interface Product
{

}

class ConcreteProductA : Product
{
}

class ConcreteProductB : Product
{
}

abstract class Creator
{
public abstract Product FactoryMethod(string type);
}

class ConcreteCreator : Creator
{
public override Product FactoryMethod(string type)
{
switch (type)
{
case "A": return new ConcreteProductA();
case "B": return new ConcreteProductB();
default: throw new ArgumentException("Invalid type", "type");
}
}
}



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

// Liskov Substitution Principle

namespace ManualResetEvent_
{
      // The interface

    interface IFactory
    {
        void Drive(int km);
    }

    //Class CreateProduct whih implement the interface IProduct
    class sctoor : IFactory
    {
        public void Drive(int kms)
        {
            Console.WriteLine("Scooter : My milage is " + kms + " Kms");
        }
    }

    class bike : IFactory
    {
        public void Drive(int kms)
        {
            Console.WriteLine("Bike : My milage is " + kms + " Kms");
        }
    }

    //Abstract Class creator : which declare a factory method and that is implemented by the inheriting class  and this method returns object of type product
    abstract class VehicleFactory
    {

        public abstract IFactory factoryMenthod(string type);
    }

    //class which implement the cretaor class and method "factory" and gets the product

    class ConcreteVehicleFactory : VehicleFactory
    {

        public override IFactory factoryMenthod(string type)
        {
            switch (type)
            {
                case "scooter": return new sctoor();
                case "bike": return new bike();
                default: throw new ArgumentException("No Object of Mentioned type", "type");
            }
        }
    }



    class Progran
    {
        public static void Main()
        {
            VehicleFactory factory = new ConcreteVehicleFactory();
            IFactory scooter = factory.factoryMenthod("scooter");
            scooter.Drive(20);

            IFactory Bike = factory.factoryMenthod("bike");
            Bike.Drive(30);

            Console.ReadLine();


        }
    }

}

Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6