Factory Design Pattern

When we code using OOP paradigm, we might have to deal with creating objects of classes, which implement a common interface or extend the same class. In this situation, it is recommended to use a Factory pattern. What it basically does is, that it takes on the responsibility of creating objects, making this process more generic and consequently, more clear and readable.

Let us look at the example where we need to create objects for different models of vehicles. All models will implement a Vehicle interface

interface Vehicle {
	public function getCompany(): string;
}

class Mustang implements Vehicle {

	public function __construct(string $companyName)
	{
	    $this->company = $companyName;
	}

	public function getCompany(): string
	{
	     return $this->company;
	}

}

class Beetle implements Vehicle {

	public function __construct()
	{
	    $this->company = 'VW';
	}

	public function getCompany(): string
	{
	     return $this->company;
	}
}

Now, we are going to declare a Factory class, which will create instances of the above classes according to the $modelName parameter passed to its createModel() method.

class ModelFactory {

	public static function createModel(string $modelName) {
		switch ($modelName) {
			case 'Mustang':
				$model = new Mustang('Ford');
				break;
			
			case 'Beetle':
				$model = new Beetle();
				break;
		}

		return $model;
	}
}

Having done this, we are set to create objects by using our Factory class

$beetle = ModelFactory::createModel('Beetle');

echo $beetle->getCompany(); //outputs 'VW'

The main advantage of this pattern is that it puts all logic involved in creating objects in one place, so when you want to need changes you do it only in that particular place.

Leave a Reply

Your email address will not be published. Required fields are marked *