Design Patterns Made Easy – Factory Pattern

Factory Pattern

Factory Pattern helps to instantiate complex objects keeping future changes in mind. In this case, you don’t use the new keyword to directly instantiate an object of a class, but use a static method of another factory class. This helps to wrap up complex and dynamic construction of objects or helps in cases where the right class to instantiate depends on input parameters.


class Person {
	private $name;
	protected $type;

	function __construct($_name, $_type) {
		$this->name = $_name;
		$this->type = $_type;
	}
}

interface iPerson {
	function behave();
}

class Good_Person extends Person implements iPerson {
	protected $type;

	function __construct($_name) {
		$this->name = $_name;
		$this->type = "GOOD";
	}

	function behave() {
		echo $this->name." is a ".$this->type." person!";
	}
}

class Bad_Person extends Person implements iPerson {
	protected $type;

	function __construct($_name) {
		$this->name = $_name;
		$this->type = "BAD";
	}

	function behave() {
		echo $this->name." is a ".$this->type." person!";
	}
}

class PersonFactory {
	function create($name, $type) {
		$type = ucwords(strtolower($type));
		$class = $type."_Person";
		if (class_exists($class)) {
			return new $class($name);
		} else {
			throw new Exception("Invalid type");
		} 
	}
}

$type_of_person = "GOOD"; //This could be $_POST['person_type']
$good_person = PersonFactory::create("Floyd", $type_of_person);
$good_person->behave();

Now the construction logic has been separated to the Factory class and therefore the code is much more flexible and maintainable in the long run. If the logic behind instantiating the object changes at some point, all we need to do is update the factory create method and leave the rest of the code as they were.

One thought on “Design Patterns Made Easy – Factory Pattern

  1. Pingback: Design Patterns Made Easy - OOP Concepts

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>