Patterns: Creational: Factory Method

Defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Allows programmers to request object and have the correct type created behind the scene and returned.

 

 

 

 

 

CarFactory Example

    public class CarFactory
    {
        
        public static void GetACar()
        {
            var factory = new SedanCarFactory() as IVehicleFactory;
            var myHonda = factory.GetCar("Honda");
            var myKia = factory.GetCar("Kia");
            Console.WriteLine($"Honda Price is: {myHonda.Price}, Kia Price is: {myKia.Price}");
        }
    }


    // Product
    public abstract class ICar
    {
        public decimal Price { get; set; }
    }

    // Concrete Product
    public class HondaCar : ICar
    {
        public HondaCar()
        {
            Price = 15000;
        }
    }

    // Concrete Product
    public class KiaCar : ICar
    {
        public KiaCar()
        {
            Price = 16000;
        }
    }

    // Concrete Product
    public class ChevyTruck : ICar
    {
        public ChevyTruck()
        {
            Price = 25000;
        }
    }

    //Creator
    interface IVehicleFactory
    {
        ICar GetCar(string brandName);
    }

    //Concrete Creators
    public class SedanCarFactory : IVehicleFactory
    {
        public ICar GetCar(string brandName)
        {
            if(brandName == "Honda")
            {
                return new HondaCar();
            } else if (brandName == "Kia")
            {
                return new KiaCar();
            } else
            {
                throw new ArgumentException("Invalid Brand Name");
            }
        }
    }

 

Output

Honda Price is: 15000, Kia Price is: 16000