DEV Community

Artur Lasota
Artur Lasota

Posted on

Design patterns: Simple factory

The simple factory is one of the creational design patterns. It creates objects with the same interface. The concrete object is created depend on arguments in the method.

Example:

Let assume that we like to have different configs for an application depend on the environment. So we create two classes:

class ConfigProd implements ConfigInterface
{
    public function getDatabaseName(): string
    {
        return 'database_prod';
    }
}

class ConfigDev implements ConfigInterface
{
    public function getDatabaseName(): string
    {
        return 'database_dev';
    }
}

Each class implements the same interface:

interface ConfigInterface
{
    public function getDatabaseName(): string;
}


And of course we have a simple factory:

class ConfigFactory
{
    public function createConfig(string $environment): ConfigInterface
    {
        switch ($environment) {
            case 'dev':
                return new ConfigDev();
            case 'prod':
                return new ConfigProd();
        }
    }
}

If we need production configuration then we pass string prod to factory method and we get production configuration. This same for develop environment.

$configProd = (new ConfigFactory())->createConfig('prod');
$configDev = (new ConfigFactory())->createConfig('dev');

So it's all.

Logic in the factory can be more complicated but we don't need to worry about this. We only take configuration where we need it.

P.S.
It's hard to find a good example. If you have good let me know in comments. Thanks.

Source:
https://medium.com/nestedif/java-simple-factory-pattern-9c2538dd0265

Source code:
https://github.com/lasotaartur/design-patterns/tree/master/Creational/SimplyFactory

Top comments (0)