C# | Factory Design Pattern | Creational Design Pattern
Defines an interface for creating an object, but let subclasses decide which
class to instantiate. Factory Method lets a class defer instantiation to
subclasses.
This structural code demonstrates the Factory method offering great
flexibility in creating different objects. The Abstract class may provide a
default object, but each subclass can instantiate an extended version of the
object.
public interface ICar
{
    void Start();
}
public class SixSeater : ICar
{
    public void Start()
    {
        throw new NotImplementedException();
    }
}
public class FourSeater : ICar
{
    public void Start()
    {
        throw new NotImplementedException();
    }
}
public class CarFactory
{
    public ICar GetCar(string carType)
    { 
        switch(carType)
        {
            case "SixSeater":
                return new SixSeater();
            case "FourSeater":
                return new FourSeater();
        }
        return null;
    }
}
internal class Program
{
    static void Main(string[] args)
    {
        CarFactory factory = new CarFactory();
        ICar sixSeater = factory.GetCar("SixSeater");
        ICar fourSeater = factory.GetCar("FourSeater");
    }
}
When to use it?
The process of objects creation is required to centralize
within the application.
A class (creator) will not know what classes it will be
required to create.

Comments
Post a Comment