Design pattern in PHP: Simple Factory Pattern

Simple factory pattern, also known as static factory method pattern, it belongs to the class creation pattern. In the simple factory pattern, you can return instances of different classes based on different parameters. The simple factory pattern specifically defines a class to be responsible for creating instances of other classes, and the created instances usually have a same parent class.

What problems can it solve?

Same as Factory Method Pattern, Simple Factory Pattern is designed for solving the problem of how to create object instances which inherit from a same abstract class. It is often used in some very simple object-creation scenarios.

Strictly speaking, the simple factory pattern is not actually a design pattern, it looks more like a kind of coding habit.

What simple factory pattern can do?

The simple factory methods return instances of different classes based on different parameters, and the created instances usually have a common parent class.

Implementation

Let’s take a look an example of simple factory pattern in PHP.

Step 1: create abstract product class.

/**
 * abstract product class
 */
abstract class Color
{
	abstract public function paint();
}

Step 2: create 3 concrete color product class which inherit above abstract class.

/**
 * concrete red class
 */
class RedColor extends Color
{
	public function paint()
	{
		echo "i am red\n";
	}
}

/**
 * concrete green class
 */
class GreenColor extends Color
{
	public function paint()
	{
		echo "i am green\n";
	}
}

/**
 * concrete blue class
 */
class BlueColor extends Color
{
	public function paint()
	{
		echo "i am blue\n";
	}
}

Step 3: create factory class.

/**
 * factory
 */
class ColorFactory
{
	
	public static function get($color)
	{
		$className = $color . "Color";
		if (class_exists($className)) {
			return new $className;
		}

		throw new Exception("{$color} does not exists");
	}
}

Step 4: do some test.

try {
	$color = ColorFactory::get('Red');
	$color->paint();	
} catch (Exception $e) {
	echo $e->getMessage();
}

Step 5: run the script and check the result.

$  php simplefactory.php
i am red

The example above is a very simple scenario. Hope it can help you.

RSS