Creational Design Patterns

In plain words

Creational patterns are focused towards how to instantiate an object or group of related objects.

Wikipedia says

In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

Simple Factory

Real world example

Consider, you are building a house and you need doors. You can either put on your carpenter clothes, bring some wood, glue, nails and all the tools required to build the door and start building it in your house or you can simply call the factory and get the built door delivered to you so that you don't need to learn anything about the door making or to deal with the mess that comes with making it.

In plain words

Simple factory simply generates an instance for client without exposing any instantiation logic to the client

Wikipedia says

In object-oriented programming (OOP), a factory is an object for creating other objects – formally a factory is a function or method that returns objects of a varying prototype or class from some method call, which is assumed to be "new".

Programmatic Example

First of all we have a door interface and the implementation

  1. interface Door
  2. {
  3. public function getWidth(): float;
  4. public function getHeight(): float;
  5. }
  6.  
  7. class WoodenDoor implements Door
  8. {
  9. protected $width;
  10. protected $height;
  11.  
  12. public function __construct(float $width, float $height)
  13. {
  14. $this->width = $width;
  15. $this->height = $height;
  16. }
  17.  
  18. public function getWidth(): float
  19. {
  20. return $this->width;
  21. }
  22.  
  23. public function getHeight(): float
  24. {
  25. return $this->height;
  26. }
  27. }

Then we have our door factory that makes the door and returns it

  1. class DoorFactory
  2. {
  3. public static function makeDoor($width, $height): Door
  4. {
  5. return new WoodenDoor($width, $height);
  6. }
  7. }

And then it can be used as

  1. // Make me a door of 100x200
  2. $door = DoorFactory::makeDoor(100, 200);
  3.  
  4. echo 'Width: ' . $door->getWidth();
  5. echo 'Height: ' . $door->getHeight();
  6.  
  7. // Make me a door of 50x100
  8. $door2 = DoorFactory::makeDoor(50, 100);

When to Use

When creating an object is not just a few assignments and involves some logic, it makes sense to put it in a dedicated factory instead of repeating the same code everywhere.

Factory Method

Real world example

Consider the case of a hiring manager. It is impossible for one person to interview for each of the positions. Based on the job opening, she has to decide and delegate the interview steps to different people.

In plain words

It provides a way to delegate the instantiation logic to child classes.

Wikipedia says

In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.

Programmatic Example

Taking our hiring manager example above. First of all we have an interviewer interface and some implementations for it

  1. interface Interviewer
  2. {
  3. public function askQuestions();
  4. }
  5.  
  6. class Developer implements Interviewer
  7. {
  8. public function askQuestions()
  9. {
  10. echo 'Asking about design patterns!';
  11. }
  12. }
  13.  
  14. class CommunityExecutive implements Interviewer
  15. {
  16. public function askQuestions()
  17. {
  18. echo 'Asking about community building';
  19. }
  20. }

Now let us create our HiringManager

  1. abstract class HiringManager
  2. {
  3.  
  4. // Factory method
  5. abstract protected function makeInterviewer(): Interviewer;
  6.  
  7. public function takeInterview()
  8. {
  9. $interviewer = $this->makeInterviewer();
  10. $interviewer->askQuestions();
  11. }
  12. }

Now any child can extend it and provide the required interviewer

  1. class DevelopmentManager extends HiringManager
  2. {
  3. protected function makeInterviewer(): Interviewer
  4. {
  5. return new Developer();
  6. }
  7. }
  8.  
  9. class MarketingManager extends HiringManager
  10. {
  11. protected function makeInterviewer(): Interviewer
  12. {
  13. return new CommunityExecutive();
  14. }
  15. }

and then it can be used as

  1. $devManager = new DevelopmentManager();
  2. $devManager->takeInterview(); // Output: Asking about design patterns
  3.  
  4. $marketingManager = new MarketingManager();
  5. $marketingManager->takeInterview(); // Output: Asking about community building.

When to use

Useful when there is some generic processing in a class but the required sub-class is dynamically decided at runtime. Or putting it in other words, when the client doesn't know what exact sub-class it might need.

Abstract Factory

Real world example

Extending our door example from Simple Factory. Based on your needs you might get a wooden door from a wooden door shop, iron door from an iron shop or a PVC door from the relevant shop. Plus you might need a guy with different kind of specialities to fit the door, for example a carpenter for wooden door, welder for iron door etc. As you can see there is a dependency between the doors now, wooden door needs carpenter, iron door needs a welder etc.

In plain words

A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes.

Wikipedia says

The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes

Programmatic Example

Translating the door example above. First of all we have our Door interface and some implementation for it

  1. interface Door
  2. {
  3. public function getDescription();
  4. }
  5.  
  6. class WoodenDoor implements Door
  7. {
  8. public function getDescription()
  9. {
  10. echo 'I am a wooden door';
  11. }
  12. }
  13.  
  14. class IronDoor implements Door
  15. {
  16. public function getDescription()
  17. {
  18. echo 'I am an iron door';
  19. }
  20. }

Then we have some fitting experts for each door type

  1. interface DoorFittingExpert
  2. {
  3. public function getDescription();
  4. }
  5.  
  6. class Welder implements DoorFittingExpert
  7. {
  8. public function getDescription()
  9. {
  10. echo 'I can only fit iron doors';
  11. }
  12. }
  13.  
  14. class Carpenter implements DoorFittingExpert
  15. {
  16. public function getDescription()
  17. {
  18. echo 'I can only fit wooden doors';
  19. }
  20. }

Now we have our abstract factory that would let us make family of related objects i.e. wooden door factory would create a wooden door and wooden door fitting expert and iron door factory would create an iron door and iron door fitting expert

  1. interface DoorFactory
  2. {
  3. public function makeDoor(): Door;
  4. public function makeFittingExpert(): DoorFittingExpert;
  5. }
  6.  
  7. // Wooden factory to return carpenter and wooden door
  8. class WoodenDoorFactory implements DoorFactory
  9. {
  10. public function makeDoor(): Door
  11. {
  12. return new WoodenDoor();
  13. }
  14.  
  15. public function makeFittingExpert(): DoorFittingExpert
  16. {
  17. return new Carpenter();
  18. }
  19. }
  20.  
  21. // Iron door factory to get iron door and the relevant fitting expert
  22. class IronDoorFactory implements DoorFactory
  23. {
  24. public function makeDoor(): Door
  25. {
  26. return new IronDoor();
  27. }
  28.  
  29. public function makeFittingExpert(): DoorFittingExpert
  30. {
  31. return new Welder();
  32. }
  33. }

And then it can be used as

  1. $woodenFactory = new WoodenDoorFactory();
  2.  
  3. $door = $woodenFactory->makeDoor();
  4. $expert = $woodenFactory->makeFittingExpert();
  5.  
  6. $door->getDescription(); // Output: I am a wooden door
  7. $expert->getDescription(); // Output: I can only fit wooden doors
  8.  
  9. // Same for Iron Factory
  10. $ironFactory = new IronDoorFactory();
  11.  
  12. $door = $ironFactory->makeDoor();
  13. $expert = $ironFactory->makeFittingExpert();
  14.  
  15. $door->getDescription(); // Output: I am an iron door
  16. $expert->getDescription(); // Output: I can only fit iron doors

As you can see the wooden door factory has encapsulated the carpenter and the wooden door also iron door factory has encapsulated the iron door and welder. And thus it had helped us make sure that for each of the created door, we do not get a wrong fitting expert.

When to use

When there are interrelated dependencies with not-that-simple creation logic involved

Builder

Real world example

Imagine you are at Hardee's and you order a specific deal, lets say, "Big Hardee" and they hand it over to you without any questions; this is the example of simple factory. But there are cases when the creation logic might involve more steps. For example you want a customized Subway deal, you have several options in how your burger is made e.g what bread do you want what types of sauces would you like What cheese would you want etc. In such cases builder pattern comes to the rescue.

In plain words

Allows you to create different flavors of an object while avoiding constructor pollution. Useful when there could be several flavors of an object. Or when there are a lot of steps involved in creation of an object.

Wikipedia says

The builder pattern is an object creation software design pattern with the intentions of finding a solution to the telescoping constructor anti-pattern.

Having said that let me add a bit about what telescoping constructor anti-pattern is. At one point or the other we have all seen a constructor like below:

  1. public function __construct($size, $cheese = true, $pepperoni = true, $tomato = false, $lettuce = true)
  2. {
  3. }

As you can see; the number of constructor parameters can quickly get out of hand and it might become difficult to understand the arrangement of parameters. Plus this parameter list could keep on growing if you would want to add more options in future. This is called telescoping constructor anti-pattern.

Programmatic Example

The sane alternative is to use the builder pattern. First of all we have our burger that we want to make

  1. class Burger
  2. {
  3. protected $size;
  4.  
  5. protected $cheese = false;
  6. protected $pepperoni = false;
  7. protected $lettuce = false;
  8. protected $tomato = false;
  9.  
  10. public function __construct(BurgerBuilder $builder)
  11. {
  12. $this->size = $builder->size;
  13. $this->cheese = $builder->cheese;
  14. $this->pepperoni = $builder->pepperoni;
  15. $this->lettuce = $builder->lettuce;
  16. $this->tomato = $builder->tomato;
  17. }
  18. }

And then we have the builder

  1. class BurgerBuilder
  2. {
  3. public $size;
  4.  
  5. public $cheese = false;
  6. public $pepperoni = false;
  7. public $lettuce = false;
  8. public $tomato = false;
  9.  
  10. public function __construct(int $size)
  11. {
  12. $this->size = $size;
  13. }
  14.  
  15. public function addPepperoni()
  16. {
  17. $this->pepperoni = true;
  18. return $this;
  19. }
  20.  
  21. public function addLettuce()
  22. {
  23. $this->lettuce = true;
  24. return $this;
  25. }
  26.  
  27. public function addCheese()
  28. {
  29. $this->cheese = true;
  30. return $this;
  31. }
  32.  
  33. public function addTomato()
  34. {
  35. $this->tomato = true;
  36. return $this;
  37. }
  38.  
  39. public function build(): Burger
  40. {
  41. return new Burger($this);
  42. }
  43. }

And then it can be used as:

  1. $burger = (new BurgerBuilder(14))
  2. ->addPepperoni()
  3. ->addLettuce()
  4. ->addTomato()
  5. ->build();

When to use

When there could be several flavors of an object and to avoid the constructor telescoping. The key difference from the factory pattern is that; factory pattern is to be used when the creation is a one step process while builder pattern is to be used when the creation is a multi step process.

Prototype

Real world example

Remember dolly The sheep that was cloned! Lets not get into the details but the key point here is that it is all about cloning

In plain words

Create object based on an existing object through cloning.

Wikipedia says

The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects.

In short, it allows you to create a copy of an existing object and modify it to your needs, instead of going through the trouble of creating an object from scratch and setting it up.

Programmatic Example

In PHP, it can be easily done using clone

  1. class Sheep
  2. {
  3. protected $name;
  4. protected $category;
  5.  
  6. public function __construct(string $name, string $category = 'Mountain Sheep')
  7. {
  8. $this->name = $name;
  9. $this->category = $category;
  10. }
  11.  
  12. public function setName(string $name)
  13. {
  14. $this->name = $name;
  15. }
  16.  
  17. public function getName()
  18. {
  19. return $this->name;
  20. }
  21.  
  22. public function setCategory(string $category)
  23. {
  24. $this->category = $category;
  25. }
  26.  
  27. public function getCategory()
  28. {
  29. return $this->category;
  30. }
  31. }

Then it can be cloned like below

  1. $original = new Sheep('Jolly');
  2. echo $original->getName(); // Jolly
  3. echo $original->getCategory(); // Mountain Sheep
  4.  
  5. // Clone and modify what is required
  6. $cloned = clone $original;
  7. $cloned->setName('Dolly');
  8. echo $cloned->getName(); // Dolly
  9. echo $cloned->getCategory(); // Mountain sheep

Also you could use the magic method __clone to modify the cloning behavior.

When to use

When an object is required that is similar to existing object or when the creation would be expensive as compared to cloning.

Singleton

Real world example

There can only be one president of a country at a time. The same president has to be brought to action, whenever duty calls. President here is singleton.

In plain words

Ensures that only one object of a particular class is ever created.

Wikipedia says

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

Singleton pattern is actually considered an anti-pattern and overuse of it should be avoided. It is not necessarily bad and could have some valid use-cases but should be used with caution because it introduces a global state in your application and change to it in one place could affect in the other areas and it could become pretty difficult to debug. The other bad thing about them is it makes your code tightly coupled plus mocking the singleton could be difficult.

Programmatic Example

To create a singleton, make the constructor private, disable cloning, disable extension and create a static variable to house the instance

  1. final class President
  2. {
  3. private static $instance;
  4.  
  5. private function __construct()
  6. {
  7. // Hide the constructor
  8. }
  9.  
  10. public static function getInstance(): President
  11. {
  12. if (!self::$instance) {
  13. self::$instance = new self();
  14. }
  15.  
  16. return self::$instance;
  17. }
  18.  
  19. private function __clone()
  20. {
  21. // Disable cloning
  22. }
  23.  
  24. private function __wakeup()
  25. {
  26. // Disable unserialize
  27. }
  28. }

Then in order to use

  1. $president1 = President::getInstance();
  2. $president2 = President::getInstance();
  3.  
  4. var_dump($president1 === $president2); // true