Development Blog

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

Static Factory Pattern

Similar to the AbstractFactory, this pattern is used to create series of related or dependent objects.
2
Likes
2 years ago
Design Patterns: Creational
Purpose

Similar to the AbstractFactory, this pattern is used to create series of related or dependent objects. The difference between this and the abstract factory pattern is that the static factory pattern uses just one static method to create all types of objects it can create. It is usually named factory, build or make.

Examples
UML


Code

Formatter


namespace DesignPatterns\Creational\StaticFactory;

interface Formatter
{
    public function format(string $input): string;
}

FormatNumber


namespace DesignPatterns\Creational\StaticFactory;

class FormatNumber implements Formatter
{
    public function format(string $input): string
    {
        return number_format((int) $input);
    }
}

FormatString


namespace DesignPatterns\Creational\StaticFactory;

class FormatString implements Formatter
{
    public function format(string $input): string
    {
        return $input;
    }
}

StaticFactory


namespace DesignPatterns\Creational\StaticFactory;

use InvalidArgumentException;

/**
* Note1: Remember, static means global state which is evil because it can't be mocked for tests
* Note2: Cannot be subclassed or mock-upped or have multiple different instances.
*/
final class StaticFactory
{
    public static function factory(string $type): Formatter 
    {
        if ($type == 'number') {
            return new FormatNumber();
        } elseif ($type == 'string') {
           return new FormatString();
        }

        throw new InvalidArgumentException('Unknown format given');
    }
}