Development Blog

Collection of development articles I've put together...
Return to articles

Simple Factory Pattern

SimpleFactory is a simple factory pattern. It differs from the static factory because it is not static
1
Likes
2 years ago
Design Patterns: Creational
Purpose

SimpleFactory is a simple factory pattern.

It differs from the static factory because it is not static. Therefore, you can have multiple factories, differently parameterised, you can subclass it and you can mock it.

It has some advantages over a Static Factory but a Static Factory closes classes for modification, this technically doesn’t (if you needed to change the Simple Factory, you’d be adjusting the class its being called from).

Examples
UML


Code

Bicycle


namespace DesignPatterns\Creational\SimpleFactory;

class Bicycle
{
    public function driveTo(string $destination)
    {
    }
}

SimpleFactory


namespace DesignPatterns\Creational\SimpleFactory;

class SimpleFactory
{
    public function createBicycle(): Bicycle
    {
        return new Bicycle();
    }
}