Structural Design Patterns

In plain words

Structural patterns are mostly concerned with object composition or in other words how the entities can use each other. Or yet another explanation would be, they help in answering "How to build a software component"

Wikipedia says

In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.

Adapter

Real world example

Consider that you have some pictures in your memory card and you need to transfer them to your computer. In order to transfer them you need some kind of adapter that is compatible with your computer ports so that you can attach memory card to your computer. In this case card reader is an adapter.Another example would be the famous power adapter; a three legged plug can't be connected to a two pronged outlet, it needs to use a power adapter that makes it compatible with the two pronged outlet.Yet another example would be a translator translating words spoken by one person to another

In plain words

Adapter pattern lets you wrap an otherwise incompatible object in an adapter to make it compatible with another class.

Wikipedia says

In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code.

Programmatic Example

Consider a game where there is a hunter and he hunts lions.

First we have an interface Lion that all types of lions have to implement

  1. interface Lion
  2. {
  3. public function roar();
  4. }
  5.  
  6. class AfricanLion implements Lion
  7. {
  8. public function roar()
  9. {
  10. }
  11. }
  12.  
  13. class AsianLion implements Lion
  14. {
  15. public function roar()
  16. {
  17. }
  18. }

And hunter expects any implementation of Lion interface to hunt.

  1. class Hunter
  2. {
  3. public function hunt(Lion $lion)
  4. {
  5. $lion->roar();
  6. }
  7. }

Now let's say we have to add a WildDog in our game so that hunter can hunt that also. But we can't do that directly because dog has a different interface. To make it compatible for our hunter, we will have to create an adapter that is compatible

  1. // This needs to be added to the game
  2. class WildDog
  3. {
  4. public function bark()
  5. {
  6. }
  7. }
  8.  
  9. // Adapter around wild dog to make it compatible with our game
  10. class WildDogAdapter implements Lion
  11. {
  12. protected $dog;
  13.  
  14. public function __construct(WildDog $dog)
  15. {
  16. $this->dog = $dog;
  17. }
  18.  
  19. public function roar()
  20. {
  21. $this->dog->bark();
  22. }
  23. }

And now the WildDog can be used in our game using WildDogAdapter.

  1. $wildDog = new WildDog();
  2. $wildDogAdapter = new WildDogAdapter($wildDog);
  3.  
  4. $hunter = new Hunter();
  5. $hunter->hunt($wildDogAdapter);

Bridge

Real world example

Consider you have a website with different pages and you are supposed to allow the user to change the theme. What would you do Create multiple copies of each of the pages for each of the themes or would you just create separate theme and load them based on the user's preferences Bridge pattern allows you to do the second i.e.

With and without the bridge pattern

In Plain Words

Bridge pattern is about preferring composition over inheritance. Implementation details are pushed from a hierarchy to another object with a separate hierarchy.

Wikipedia says

The bridge pattern is a design pattern used in software engineering that is meant to "decouple an abstraction from its implementation so that the two can vary independently"

Programmatic Example

Translating our WebPage example from above. Here we have the WebPage hierarchy

  1. interface WebPage
  2. {
  3. public function __construct(Theme $theme);
  4. public function getContent();
  5. }
  6.  
  7. class About implements WebPage
  8. {
  9. protected $theme;
  10.  
  11. public function __construct(Theme $theme)
  12. {
  13. $this->theme = $theme;
  14. }
  15.  
  16. public function getContent()
  17. {
  18. return "About page in " . $this->theme->getColor();
  19. }
  20. }
  21.  
  22. class Careers implements WebPage
  23. {
  24. protected $theme;
  25.  
  26. public function __construct(Theme $theme)
  27. {
  28. $this->theme = $theme;
  29. }
  30.  
  31. public function getContent()
  32. {
  33. return "Careers page in " . $this->theme->getColor();
  34. }
  35. }

And the separate theme hierarchy

  1. interface Theme
  2. {
  3. public function getColor();
  4. }
  5.  
  6. class DarkTheme implements Theme
  7. {
  8. public function getColor()
  9. {
  10. return 'Dark Black';
  11. }
  12. }
  13. class LightTheme implements Theme
  14. {
  15. public function getColor()
  16. {
  17. return 'Off white';
  18. }
  19. }
  20. class AquaTheme implements Theme
  21. {
  22. public function getColor()
  23. {
  24. return 'Light blue';
  25. }
  26. }

And both the hierarchies

  1. $darkTheme = new DarkTheme();
  2.  
  3. $about = new About($darkTheme);
  4. $careers = new Careers($darkTheme);
  5.  
  6. echo $about->getContent(); // "About page in Dark Black";
  7. echo $careers->getContent(); // "Careers page in Dark Black";

Composite

Real world example

Every organization is composed of employees. Each of the employees has the same features i.e. has a salary, has some responsibilities, may or may not report to someone, may or may not have some subordinates etc.

In plain words

Composite pattern lets clients treat the individual objects in a uniform manner.

Wikipedia says

In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects is to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

Programmatic Example

Taking our employees example from above. Here we have different employee types

  1. interface Employee
  2. {
  3. public function __construct(string $name, float $salary);
  4. public function getName(): string;
  5. public function setSalary(float $salary);
  6. public function getSalary(): float;
  7. public function getRoles(): array;
  8. }
  9.  
  10. class Developer implements Employee
  11. {
  12. protected $salary;
  13. protected $name;
  14. protected $roles;
  15.  
  16. public function __construct(string $name, float $salary)
  17. {
  18. $this->name = $name;
  19. $this->salary = $salary;
  20. }
  21.  
  22. public function getName(): string
  23. {
  24. return $this->name;
  25. }
  26.  
  27. public function setSalary(float $salary)
  28. {
  29. $this->salary = $salary;
  30. }
  31.  
  32. public function getSalary(): float
  33. {
  34. return $this->salary;
  35. }
  36.  
  37. public function getRoles(): array
  38. {
  39. return $this->roles;
  40. }
  41. }
  42.  
  43. class Designer implements Employee
  44. {
  45. protected $salary;
  46. protected $name;
  47. protected $roles;
  48.  
  49. public function __construct(string $name, float $salary)
  50. {
  51. $this->name = $name;
  52. $this->salary = $salary;
  53. }
  54.  
  55. public function getName(): string
  56. {
  57. return $this->name;
  58. }
  59.  
  60. public function setSalary(float $salary)
  61. {
  62. $this->salary = $salary;
  63. }
  64.  
  65. public function getSalary(): float
  66. {
  67. return $this->salary;
  68. }
  69.  
  70. public function getRoles(): array
  71. {
  72. return $this->roles;
  73. }
  74. }

Then we have an organization which consists of several different types of employees

  1. class Organization
  2. {
  3. protected $employees;
  4.  
  5. public function addEmployee(Employee $employee)
  6. {
  7. $this->employees[] = $employee;
  8. }
  9.  
  10. public function getNetSalaries(): float
  11. {
  12. $netSalary = 0;
  13.  
  14. foreach ($this->employees as $employee) {
  15. $netSalary += $employee->getSalary();
  16. }
  17.  
  18. return $netSalary;
  19. }
  20. }

And then it can be used as

  1. // Prepare the employees
  2. $john = new Developer('John Doe', 12000);
  3. $jane = new Designer('Jane Doe', 15000);
  4.  
  5. // Add them to organization
  6. $organization = new Organization();
  7. $organization->addEmployee($john);
  8. $organization->addEmployee($jane);
  9.  
  10. echo "Net salaries: " . $organization->getNetSalaries(); // Net Salaries: 27000

☕ Decorator

Real world example

Imagine you run a car service shop offering multiple services. Now how do you calculate the bill to be charged You pick one service and dynamically keep adding to it the prices for the provided services till you get the final cost. Here each type of service is a decorator.

In plain words

Decorator pattern lets you dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class.

Wikipedia says

In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern.

Programmatic Example

Lets take coffee for example. First of all we have a simple coffee implementing the coffee interface

  1. interface Coffee
  2. {
  3. public function getCost();
  4. public function getDescription();
  5. }
  6.  
  7. class SimpleCoffee implements Coffee
  8. {
  9. public function getCost()
  10. {
  11. return 10;
  12. }
  13.  
  14. public function getDescription()
  15. {
  16. return 'Simple coffee';
  17. }
  18. }

We want to make the code extensible to allow options to modify it if required. Lets make some add-ons (decorators)

  1. class MilkCoffee implements Coffee
  2. {
  3. protected $coffee;
  4.  
  5. public function __construct(Coffee $coffee)
  6. {
  7. $this->coffee = $coffee;
  8. }
  9.  
  10. public function getCost()
  11. {
  12. return $this->coffee->getCost() + 2;
  13. }
  14.  
  15. public function getDescription()
  16. {
  17. return $this->coffee->getDescription() . ', milk';
  18. }
  19. }
  20.  
  21. class WhipCoffee implements Coffee
  22. {
  23. protected $coffee;
  24.  
  25. public function __construct(Coffee $coffee)
  26. {
  27. $this->coffee = $coffee;
  28. }
  29.  
  30. public function getCost()
  31. {
  32. return $this->coffee->getCost() + 5;
  33. }
  34.  
  35. public function getDescription()
  36. {
  37. return $this->coffee->getDescription() . ', whip';
  38. }
  39. }
  40.  
  41. class VanillaCoffee implements Coffee
  42. {
  43. protected $coffee;
  44.  
  45. public function __construct(Coffee $coffee)
  46. {
  47. $this->coffee = $coffee;
  48. }
  49.  
  50. public function getCost()
  51. {
  52. return $this->coffee->getCost() + 3;
  53. }
  54.  
  55. public function getDescription()
  56. {
  57. return $this->coffee->getDescription() . ', vanilla';
  58. }
  59. }

Lets make a coffee now

  1. $someCoffee = new SimpleCoffee();
  2. echo $someCoffee->getCost(); // 10
  3. echo $someCoffee->getDescription(); // Simple Coffee
  4.  
  5. $someCoffee = new MilkCoffee($someCoffee);
  6. echo $someCoffee->getCost(); // 12
  7. echo $someCoffee->getDescription(); // Simple Coffee, milk
  8.  
  9. $someCoffee = new WhipCoffee($someCoffee);
  10. echo $someCoffee->getCost(); // 17
  11. echo $someCoffee->getDescription(); // Simple Coffee, milk, whip
  12.  
  13. $someCoffee = new VanillaCoffee($someCoffee);
  14. echo $someCoffee->getCost(); // 20
  15. echo $someCoffee->getDescription(); // Simple Coffee, milk, whip, vanilla

Facade

Real world example

How do you turn on the computer "Hit the power button" you say! That is what you believe because you are using a simple interface that computer provides on the outside, internally it has to do a lot of stuff to make it happen. This simple interface to the complex subsystem is a facade.

In plain words

Facade pattern provides a simplified interface to a complex subsystem.

Wikipedia says

A facade is an object that provides a simplified interface to a larger body of code, such as a class library.

Programmatic Example

Taking our computer example from above. Here we have the computer class

  1. class Computer
  2. {
  3. public function getElectricShock()
  4. {
  5. echo "Ouch!";
  6. }
  7.  
  8. public function makeSound()
  9. {
  10. echo "Beep beep!";
  11. }
  12.  
  13. public function showLoadingScreen()
  14. {
  15. echo "Loading..";
  16. }
  17.  
  18. public function bam()
  19. {
  20. echo "Ready to be used!";
  21. }
  22.  
  23. public function closeEverything()
  24. {
  25. echo "Bup bup bup buzzzz!";
  26. }
  27.  
  28. public function sooth()
  29. {
  30. echo "Zzzzz";
  31. }
  32.  
  33. public function pullCurrent()
  34. {
  35. echo "Haaah!";
  36. }
  37. }

Here we have the facade

  1. class ComputerFacade
  2. {
  3. protected $computer;
  4.  
  5. public function __construct(Computer $computer)
  6. {
  7. $this->computer = $computer;
  8. }
  9.  
  10. public function turnOn()
  11. {
  12. $this->computer->getElectricShock();
  13. $this->computer->makeSound();
  14. $this->computer->showLoadingScreen();
  15. $this->computer->bam();
  16. }
  17.  
  18. public function turnOff()
  19. {
  20. $this->computer->closeEverything();
  21. $this->computer->pullCurrent();
  22. $this->computer->sooth();
  23. }
  24. }

Now to use the facade

  1. $computer = new ComputerFacade(new Computer());
  2. $computer->turnOn(); // Ouch! Beep beep! Loading.. Ready to be used!
  3. $computer->turnOff(); // Bup bup buzzz! Haah! Zzzzz

Flyweight

Real world example

Did you ever have fresh tea from some stall They often make more than one cup that you demanded and save the rest for any other customer so to save the resources e.g. gas etc. Flyweight pattern is all about that i.e. sharing.

In plain words

It is used to minimize memory usage or computational expenses by sharing as much as possible with similar objects.

Wikipedia says

In computer programming, flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.

Programmatic example

Translating our tea example from above. First of all we have tea types and tea maker

  1. // Anything that will be cached is flyweight.
  2. // Types of tea here will be flyweights.
  3. class KarakTea
  4. {
  5. }
  6.  
  7. // Acts as a factory and saves the tea
  8. class TeaMaker
  9. {
  10. protected $availableTea = [];
  11.  
  12. public function make($preference)
  13. {
  14. if (empty($this->availableTea[$preference])) {
  15. $this->availableTea[$preference] = new KarakTea();
  16. }
  17.  
  18. return $this->availableTea[$preference];
  19. }
  20. }

Then we have the TeaShop which takes orders and serves them

  1. class TeaShop
  2. {
  3. protected $orders;
  4. protected $teaMaker;
  5.  
  6. public function __construct(TeaMaker $teaMaker)
  7. {
  8. $this->teaMaker = $teaMaker;
  9. }
  10.  
  11. public function takeOrder(string $teaType, int $table)
  12. {
  13. $this->orders[$table] = $this->teaMaker->make($teaType);
  14. }
  15.  
  16. public function serve()
  17. {
  18. foreach ($this->orders as $table => $tea) {
  19. echo "Serving tea to table# " . $table;
  20. }
  21. }
  22. }

And it can be used as below

  1. $teaMaker = new TeaMaker();
  2. $shop = new TeaShop($teaMaker);
  3.  
  4. $shop->takeOrder('less sugar', 1);
  5. $shop->takeOrder('more milk', 2);
  6. $shop->takeOrder('without sugar', 5);
  7.  
  8. $shop->serve();
  9. // Serving tea to table# 1
  10. // Serving tea to table# 2
  11. // Serving tea to table# 5

Proxy

Real world example

Have you ever used an access card to go through a door There are multiple options to open that door i.e. it can be opened either using access card or by pressing a button that bypasses the security. The door's main functionality is to open but there is a proxy added on top of it to add some functionality. Let me better explain it using the code example below.

In plain words

Using the proxy pattern, a class represents the functionality of another class.

Wikipedia says

A proxy, in its most general form, is a class functioning as an interface to something else. A proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes. Use of the proxy can simply be forwarding to the real object, or can provide additional logic. In the proxy extra functionality can be provided, for example caching when operations on the real object are resource intensive, or checking preconditions before operations on the real object are invoked.

Programmatic Example

Taking our security door example from above. Firstly we have the door interface and an implementation of door

  1. interface Door
  2. {
  3. public function open();
  4. public function close();
  5. }
  6.  
  7. class LabDoor implements Door
  8. {
  9. public function open()
  10. {
  11. echo "Opening lab door";
  12. }
  13.  
  14. public function close()
  15. {
  16. echo "Closing the lab door";
  17. }
  18. }

Then we have a proxy to secure any doors that we want

  1. class SecuredDoor
  2. {
  3. protected $door;
  4.  
  5. public function __construct(Door $door)
  6. {
  7. $this->door = $door;
  8. }
  9.  
  10. public function open($password)
  11. {
  12. if ($this->authenticate($password)) {
  13. $this->door->open();
  14. } else {
  15. echo "Big no! It ain't possible.";
  16. }
  17. }
  18.  
  19. public function authenticate($password)
  20. {
  21. return $password === '$ecr@t';
  22. }
  23.  
  24. public function close()
  25. {
  26. $this->door->close();
  27. }
  28. }

And here is how it can be used

  1. $door = new SecuredDoor(new LabDoor());
  2. $door->open('invalid'); // Big no! It ain't possible.
  3.  
  4. $door->open('$ecr@t'); // Opening lab door
  5. $door->close(); // Closing lab door

Yet another example would be some sort of data-mapper implementation. For example, I recently made an ODM (Object Data Mapper) for MongoDB using this pattern where I wrote a proxy around mongo classes while utilizing the magic method __call(). All the method calls were proxied to the original mongo class and result retrieved was returned as it is but in case of find or findOne data was mapped to the required class objects and the object was returned instead of Cursor.