Mediator

Real world example

A general example would be when you talk to someone on your mobile phone, there is a network provider sitting between you and them and your conversation goes through it instead of being directly sent. In this case network provider is mediator.

In plain words

Mediator pattern adds a third party object (called mediator) to control the interaction between two objects (called colleagues). It helps reduce the coupling between the classes communicating with each other. Because now they don't need to have the knowledge of each other's implementation.

Wikipedia says

In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program's running behavior.

Programmatic Example

Here is the simplest example of a chat room (i.e. mediator) with users (i.e. colleagues) sending messages to each other.

First of all, we have the mediator i.e. the chat room

  1. interface ChatRoomMediator
  2. {
  3. public function showMessage(User $user, string $message);
  4. }
  5.  
  6. // Mediator
  7. class ChatRoom implements ChatRoomMediator
  8. {
  9. public function showMessage(User $user, string $message)
  10. {
  11. $time = date('M d, y H:i');
  12. $sender = $user->getName();
  13.  
  14. echo $time . '[' . $sender . ']:' . $message;
  15. }
  16. }

Then we have our users i.e. colleagues

  1. class User {
  2. protected $name;
  3. protected $chatMediator;
  4.  
  5. public function __construct(string $name, ChatRoomMediator $chatMediator) {
  6. $this->name = $name;
  7. $this->chatMediator = $chatMediator;
  8. }
  9.  
  10. public function getName() {
  11. return $this->name;
  12. }
  13.  
  14. public function send($message) {
  15. $this->chatMediator->showMessage($this, $message);
  16. }
  17. }

And the usage

  1. $mediator = new ChatRoom();
  2.  
  3. $john = new User('John Doe', $mediator);
  4. $jane = new User('Jane Doe', $mediator);
  5.  
  6. $john->send('Hi there!');
  7. $jane->send('Hey!');
  8.  
  9. // Output will be
  10. // Feb 14, 10:58 [John]: Hi there!
  11. // Feb 14, 10:58 [Jane]: Hey!

Memento

Real world example

Take the example of calculator (i.e. originator), where whenever you perform some calculation the last calculation is saved in memory (i.e. memento) so that you can get back to it and maybe get it restored using some action buttons (i.e. caretaker).

In plain words

Memento pattern is about capturing and storing the current state of an object in a manner that it can be restored later on in a smooth manner.

Wikipedia says

The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).

Usually useful when you need to provide some sort of undo functionality.

Programmatic Example

Lets take an example of text editor which keeps saving the state from time to time and that you can restore if you want.

First of all we have our memento object that will be able to hold the editor state

  1. class EditorMemento
  2. {
  3. protected $content;
  4.  
  5. public function __construct(string $content)
  6. {
  7. $this->content = $content;
  8. }
  9.  
  10. public function getContent()
  11. {
  12. return $this->content;
  13. }
  14. }

Then we have our editor i.e. originator that is going to use memento object

  1. class Editor
  2. {
  3. protected $content = '';
  4.  
  5. public function type(string $words)
  6. {
  7. $this->content = $this->content . ' ' . $words;
  8. }
  9.  
  10. public function getContent()
  11. {
  12. return $this->content;
  13. }
  14.  
  15. public function save()
  16. {
  17. return new EditorMemento($this->content);
  18. }
  19.  
  20. public function restore(EditorMemento $memento)
  21. {
  22. $this->content = $memento->getContent();
  23. }
  24. }

And then it can be used as

  1. $editor = new Editor();
  2.  
  3. // Type some stuff
  4. $editor->type('This is the first sentence.');
  5. $editor->type('This is second.');
  6.  
  7. // Save the state to restore to : This is the first sentence. This is second.
  8. $saved = $editor->save();
  9.  
  10. // Type some more
  11. $editor->type('And this is third.');
  12.  
  13. // Output: Content before Saving
  14. echo $editor->getContent(); // This is the first sentence. This is second. And this is third.
  15.  
  16. // Restoring to last saved state
  17. $editor->restore($saved);
  18.  
  19. $editor->getContent(); // This is the first sentence. This is second.

Observer

Real world example

A good example would be the job seekers where they subscribe to some job posting site and they are notified whenever there is a matching job opportunity.

In plain words

Defines a dependency between objects so that whenever an object changes its state, all its dependents are notified.

Wikipedia says

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

Programmatic example

Translating our example from above. First of all we have job seekers that need to be notified for a job posting

  1. class JobPost
  2. {
  3. protected $title;
  4.  
  5. public function __construct(string $title)
  6. {
  7. $this->title = $title;
  8. }
  9.  
  10. public function getTitle()
  11. {
  12. return $this->title;
  13. }
  14. }
  15.  
  16. class JobSeeker implements Observer
  17. {
  18. protected $name;
  19.  
  20. public function __construct(string $name)
  21. {
  22. $this->name = $name;
  23. }
  24.  
  25. public function onJobPosted(JobPost $job)
  26. {
  27. // Do something with the job posting
  28. echo 'Hi ' . $this->name . '! New job posted: '. $job->getTitle();
  29. }
  30. }

Then we have our job postings to which the job seekers will subscribe

  1. class EmploymentAgency implements Observable
  2. {
  3. protected $observers = [];
  4.  
  5. protected function notify(JobPost $jobPosting)
  6. {
  7. foreach ($this->observers as $observer) {
  8. $observer->onJobPosted($jobPosting);
  9. }
  10. }
  11.  
  12. public function attach(Observer $observer)
  13. {
  14. $this->observers[] = $observer;
  15. }
  16.  
  17. public function addJob(JobPost $jobPosting)
  18. {
  19. $this->notify($jobPosting);
  20. }
  21. }

Then it can be used as

  1. // Create subscribers
  2. $johnDoe = new JobSeeker('John Doe');
  3. $janeDoe = new JobSeeker('Jane Doe');
  4.  
  5. // Create publisher and attach subscribers
  6. $jobPostings = new EmploymentAgency();
  7. $jobPostings->attach($johnDoe);
  8. $jobPostings->attach($janeDoe);
  9.  
  10. // Add a new job and see if subscribers get notified
  11. $jobPostings->addJob(new JobPost('Software Engineer'));
  12.  
  13. // Output
  14. // Hi John Doe! New job posted: Software Engineer
  15. // Hi Jane Doe! New job posted: Software Engineer

Visitor

Real world example

Consider someone visiting Dubai. They just need a way (i.e. visa) to enter Dubai. After arrival, they can come and visit any place in Dubai on their own without having to ask for permission or to do some leg work in order to visit any place here; just let them know of a place and they can visit it. Visitor pattern lets you do just that, it helps you add places to visit so that they can visit as much as they can without having to do any legwork.

In plain words

Visitor pattern lets you add further operations to objects without having to modify them.

Wikipedia says

In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures. It is one way to follow the open/closed principle.

Programmatic example

Let's take an example of a zoo simulation where we have several different kinds of animals and we have to make them Sound. Let's translate this using visitor pattern

  1. // Visitee
  2. interface Animal
  3. {
  4. public function accept(AnimalOperation $operation);
  5. }
  6.  
  7. // Visitor
  8. interface AnimalOperation
  9. {
  10. public function visitMonkey(Monkey $monkey);
  11. public function visitLion(Lion $lion);
  12. public function visitDolphin(Dolphin $dolphin);
  13. }

Then we have our implementations for the animals

  1. class Monkey implements Animal
  2. {
  3. public function shout()
  4. {
  5. echo 'Ooh oo aa aa!';
  6. }
  7.  
  8. public function accept(AnimalOperation $operation)
  9. {
  10. $operation->visitMonkey($this);
  11. }
  12. }
  13.  
  14. class Lion implements Animal
  15. {
  16. public function roar()
  17. {
  18. echo 'Roaaar!';
  19. }
  20.  
  21. public function accept(AnimalOperation $operation)
  22. {
  23. $operation->visitLion($this);
  24. }
  25. }
  26.  
  27. class Dolphin implements Animal
  28. {
  29. public function speak()
  30. {
  31. echo 'Tuut tuttu tuutt!';
  32. }
  33.  
  34. public function accept(AnimalOperation $operation)
  35. {
  36. $operation->visitDolphin($this);
  37. }
  38. }

Let's implement our visitor

  1. class Speak implements AnimalOperation
  2. {
  3. public function visitMonkey(Monkey $monkey)
  4. {
  5. $monkey->shout();
  6. }
  7.  
  8. public function visitLion(Lion $lion)
  9. {
  10. $lion->roar();
  11. }
  12.  
  13. public function visitDolphin(Dolphin $dolphin)
  14. {
  15. $dolphin->speak();
  16. }
  17. }

And then it can be used as

  1. $monkey = new Monkey();
  2. $lion = new Lion();
  3. $dolphin = new Dolphin();
  4.  
  5. $speak = new Speak();
  6.  
  7. $monkey->accept($speak); // Ooh oo aa aa!
  8. $lion->accept($speak); // Roaaar!
  9. $dolphin->accept($speak); // Tuut tutt tuutt!

We could have done this simply by having an inheritance hierarchy for the animals but then we would have to modify the animals whenever we would have to add new actions to animals. But now we will not have to change them. For example, let's say we are asked to add the jump behavior to the animals, we can simply add that by creating a new visitor i.e.

  1. class Jump implements AnimalOperation
  2. {
  3. public function visitMonkey(Monkey $monkey)
  4. {
  5. echo 'Jumped 20 feet high! on to the tree!';
  6. }
  7.  
  8. public function visitLion(Lion $lion)
  9. {
  10. echo 'Jumped 7 feet! Back on the ground!';
  11. }
  12.  
  13. public function visitDolphin(Dolphin $dolphin)
  14. {
  15. echo 'Walked on water a little and disappeared';
  16. }
  17. }

And for the usage

  1. $jump = new Jump();
  2.  
  3. $monkey->accept($speak); // Ooh oo aa aa!
  4. $monkey->accept($jump); // Jumped 20 feet high! on to the tree!
  5.  
  6. $lion->accept($speak); // Roaaar!
  7. $lion->accept($jump); // Jumped 7 feet! Back on the ground!
  8.  
  9. $dolphin->accept($speak); // Tuut tutt tuutt!
  10. $dolphin->accept($jump); // Walked on water a little and disappeared

Strategy

Real world example

Consider the example of sorting, we implemented bubble sort but the data started to grow and bubble sort started getting very slow. In order to tackle this we implemented Quick sort. But now although the quick sort algorithm was doing better for large datasets, it was very slow for smaller datasets. In order to handle this we implemented a strategy where for small datasets, bubble sort will be used and for larger, quick sort.

In plain words

Strategy pattern allows you to switch the algorithm or strategy based upon the situation.

Wikipedia says

In computer programming, the strategy pattern (also known as the policy pattern) is a behavioural software design pattern that enables an algorithm's behavior to be selected at runtime.

Programmatic example

Translating our example from above. First of all we have our strategy interface and different strategy implementations

  1. interface SortStrategy
  2. {
  3. public function sort(array $dataset): array;
  4. }
  5.  
  6. class BubbleSortStrategy implements SortStrategy
  7. {
  8. public function sort(array $dataset): array
  9. {
  10. echo "Sorting using bubble sort";
  11.  
  12. // Do sorting
  13. return $dataset;
  14. }
  15. }
  16.  
  17. class QuickSortStrategy implements SortStrategy
  18. {
  19. public function sort(array $dataset): array
  20. {
  21. echo "Sorting using quick sort";
  22.  
  23. // Do sorting
  24. return $dataset;
  25. }
  26. }

And then we have our client that is going to use any strategy

  1. class Sorter
  2. {
  3. protected $sorter;
  4.  
  5. public function __construct(SortStrategy $sorter)
  6. {
  7. $this->sorter = $sorter;
  8. }
  9.  
  10. public function sort(array $dataset): array
  11. {
  12. return $this->sorter->sort($dataset);
  13. }
  14. }

And it can be used as

  1. $dataset = [1, 5, 4, 3, 2, 8];
  2.  
  3. $sorter = new Sorter(new BubbleSortStrategy());
  4. $sorter->sort($dataset); // Output : Sorting using bubble sort
  5.  
  6. $sorter = new Sorter(new QuickSortStrategy());
  7. $sorter->sort($dataset); // Output : Sorting using quick sort

State

Real world example

Imagine you are using some drawing application, you choose the paint brush to draw. Now the brush changes its behavior based on the selected color i.e. if you have chosen red color it will draw in red, if blue then it will be in blue etc.

In plain words

It lets you change the behavior of a class when the state changes.

Wikipedia says

The state pattern is a behavioral software design pattern that implements a state machine in an object-oriented way. With the state pattern, a state machine is implemented by implementing each individual state as a derived class of the state pattern interface, and implementing state transitions by invoking methods defined by the pattern's superclass.The state pattern can be interpreted as a strategy pattern which is able to switch the current strategy through invocations of methods defined in the pattern's interface.

Programmatic example

Let's take an example of text editor, it lets you change the state of text that is typed i.e. if you have selected bold, it starts writing in bold, if italic then in italics etc.

First of all we have our state interface and some state implementations

  1. interface WritingState
  2. {
  3. public function write(string $words);
  4. }
  5.  
  6. class UpperCase implements WritingState
  7. {
  8. public function write(string $words)
  9. {
  10. echo strtoupper($words);
  11. }
  12. }
  13.  
  14. class LowerCase implements WritingState
  15. {
  16. public function write(string $words)
  17. {
  18. echo strtolower($words);
  19. }
  20. }
  21.  
  22. class DefaultText implements WritingState
  23. {
  24. public function write(string $words)
  25. {
  26. echo $words;
  27. }
  28. }

Then we have our editor

  1. class TextEditor
  2. {
  3. protected $state;
  4.  
  5. public function __construct(WritingState $state)
  6. {
  7. $this->state = $state;
  8. }
  9.  
  10. public function setState(WritingState $state)
  11. {
  12. $this->state = $state;
  13. }
  14.  
  15. public function type(string $words)
  16. {
  17. $this->state->write($words);
  18. }
  19. }

And then it can be used as

  1. $editor = new TextEditor(new DefaultText());
  2.  
  3. $editor->type('First line');
  4.  
  5. $editor->setState(new UpperCase());
  6.  
  7. $editor->type('Second line');
  8. $editor->type('Third line');
  9.  
  10. $editor->setState(new LowerCase());
  11.  
  12. $editor->type('Fourth line');
  13. $editor->type('Fifth line');
  14.  
  15. // Output:
  16. // First line
  17. // SECOND LINE
  18. // THIRD LINE
  19. // fourth line
  20. // fifth line

Template Method

Real world example

Suppose we are getting some house built. The steps for building might look like

  • Prepare the base of house
  • Build the walls
  • Add roof
  • Add other floors

The order of these steps could never be changed i.e. you can't build the roof before building the walls etc but each of the steps could be modified for example walls can be made of wood or polyester or stone.

In plain words

Template method defines the skeleton of how a certain algorithm could be performed, but defers the implementation of those steps to the children classes.

Wikipedia says

In software engineering, the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in an operation, deferring some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm's structure.

Programmatic Example

Imagine we have a build tool that helps us test, lint, build, generate build reports (i.e. code coverage reports, linting report etc) and deploy our app on the test server.

First of all we have our base class that specifies the skeleton for the build algorithm

  1. abstract class Builder
  2. {
  3.  
  4. // Template method
  5. final public function build()
  6. {
  7. $this->test();
  8. $this->lint();
  9. $this->assemble();
  10. $this->deploy();
  11. }
  12.  
  13. abstract public function test();
  14. abstract public function lint();
  15. abstract public function assemble();
  16. abstract public function deploy();
  17. }

Then we can have our implementations

  1. class AndroidBuilder extends Builder
  2. {
  3. public function test()
  4. {
  5. echo 'Running android tests';
  6. }
  7.  
  8. public function lint()
  9. {
  10. echo 'Linting the android code';
  11. }
  12.  
  13. public function assemble()
  14. {
  15. echo 'Assembling the android build';
  16. }
  17.  
  18. public function deploy()
  19. {
  20. echo 'Deploying android build to server';
  21. }
  22. }
  23.  
  24. class IosBuilder extends Builder
  25. {
  26. public function test()
  27. {
  28. echo 'Running ios tests';
  29. }
  30.  
  31. public function lint()
  32. {
  33. echo 'Linting the ios code';
  34. }
  35.  
  36. public function assemble()
  37. {
  38. echo 'Assembling the ios build';
  39. }
  40.  
  41. public function deploy()
  42. {
  43. echo 'Deploying ios build to server';
  44. }
  45. }

And then it can be used as

  1. $androidBuilder = new AndroidBuilder();
  2. $androidBuilder->build();
  3.  
  4. // Output:
  5. // Running android tests
  6. // Linting the android code
  7. // Assembling the android build
  8. // Deploying android build to server
  9.  
  10. $iosBuilder = new IosBuilder();
  11. $iosBuilder->build();
  12.  
  13. // Output:
  14. // Running ios tests
  15. // Linting the ios code
  16. // Assembling the ios build
  17. // Deploying ios build to server

Wrap Up Folks

And that about wraps it up. I will continue to improve this, so you might want to watch/star this repository to revisit. Also, I have plans on writing the same about the architectural patterns, stay tuned for it.

Contribution

  • Report issues
  • Open pull request with improvements
  • Spread the word
  • Reach out with any feedback Twitter URL

License

License: CC BY 4.0