paulund

Simple Factory Design Pattern

Simple Factory Design Pattern

A simple factory is an object that is used to generate an instance of an object for the client.

The simplest way of understanding a factory is as an object for creating other objects.

Real World Example

For example, suppose we have three types of car and want to create a factory that builds the car classes for us.

Start with an interface to define a car:

<?php

namespace SimpleFactory;

interface Car
{

}

Each car then implements the interface:

<?php

namespace SimpleFactory;

class Tesla implements Car
{

}

The factory itself handles the creation of each car type:

<?php

namespace SimpleFactory;

class CarFactory
{
    public function makeTesla() : Car
    {
        return new Tesla;
    }

    public function makeBmw() : Car
    {
        return new Bmw;
    }

    public function makeMercedes() : Car
    {
        return new Mercedes;
    }
}

When to Use

The simple factory is useful when you need a centralised location for creating objects. If those objects must be created in a specific way with particular parameters each time, the factory pattern lets you encapsulate that logic in one place rather than duplicating it throughout the application.