lundi 25 février 2019

The meaning of Factory Pattern

What is the main meaning of using Factory Pattern?

  • At the beginning we have a Simple Factory
class FanFactory : IFanFactory
{
    public IFan CreateFan(FanType type)
    {
        switch (type)
        {
            case FanType.TableFan:
                return new TableFan();
            case FanType.CeilingFan:
                return new CeilingFan();
            case FanType.ExhaustFan:
                return new ExhaustFan();
            default:
                return new TableFan();
        }
    }
}

Although it violates the Principle of SOLID, it seems logical. Using one factory object I can create any other.

  • Factory method
static void Main(string[] args)
{
    IFanFactory fanFactory = new PropellerFanFactory();
    IFan fan = fanFactory.CreateFan();
    fan.SwitchOn();
    Console.ReadLine();
}

In this case, I could do as well:

IFan fan = new PropellerFan();
fan.SwitchOn();

What was the purpose of Factory Method? You can not see the simplification of the code in it. If we use inheritance in classes and in a child we add a method other than in the parent, then everything loses meaning.

Link to examples

Aucun commentaire:

Enregistrer un commentaire