DEV Community

Discussion on: Factory Method Design Pattern

Collapse
 
koski84 profile image
Koski84 • Edited

The quote below - taken from the Gang of Four - is very precise about the Factory Method. The Factory Method Design Pattern defines an interface for creating an object, but let sub classes decide which class to instantiate. Factory Method lets a class defer instantiating to sub classes.

Your code doesn't follow this. This is factory method pattern:

interface CarFactory
{
    ICar CreateCar();
}

class ElectricCarFactory : CarFactory
{
    ICar CreateCar()
    {
        // logic to create a electric car
    }
}

class PetrolCarFactory : CarFactory
{
    ICar CreateCar()
    {
        // logic to create a petrol car
    }
}
Collapse
 
patzistar profile image
Patrick Schadler

Chapeau, this is spot on! I am guilty of adjusting the definition ever so slightly to my preferences, but you are right. Thank you for pointing that out.