12 | A topic that can easily make anyone's mind wobble. Here I try to make them stick in to your mind (and maybe mine) by explaining them in the simplest way possible.
13 |
14 |
15 | ***
16 |
17 | Check out my [other project](http://roadmap.sh) and say "hi" on [Twitter](https://twitter.com/kamrify).
18 |
19 |
20 |
21 | |[Creational Design Patterns](#creational-design-patterns)|[Structural Design Patterns](#structural-design-patterns)|[Behavioral Design Patterns](#behavioral-design-patterns)|
22 | |:-|:-|:-|
23 | |[Simple Factory](#-simple-factory)|[Adapter](#-adapter)|[Chain of Responsibility](#-chain-of-responsibility)|
24 | |[Factory Method](#-factory-method)|[Bridge](#-bridge)|[Command](#-command)|
25 | |[Abstract Factory](#-abstract-factory)|[Composite](#-composite)|[Iterator](#-iterator)|
26 | |[Builder](#-builder)|[Decorator](#-decorator)|[Mediator](#-mediator)|
27 | |[Prototype](#-prototype)|[Facade](#-facade)|[Memento](#-memento)|
28 | |[Singleton](#-singleton)|[Flyweight](#-flyweight)|[Observer](#-observer)|
29 | ||[Proxy](#-proxy)|[Visitor](#-visitor)|
30 | |||[Strategy](#-strategy)|
31 | |||[State](#-state)|
32 | |||[Template Method](#-template-method)|
33 |
34 |
35 |
36 | Introduction
37 | =================
38 |
39 | Design patterns are solutions to recurring problems; **guidelines on how to tackle certain problems**. They are not classes, packages or libraries that you can plug into your application and wait for the magic to happen. These are, rather, guidelines on how to tackle certain problems in certain situations.
40 |
41 | > Design patterns are solutions to recurring problems; guidelines on how to tackle certain problems
42 |
43 | Wikipedia describes them as
44 |
45 | > In software engineering, a software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations.
46 |
47 | ⚠️ Be Careful
48 | -----------------
49 | - Design patterns are not a silver bullet to all your problems.
50 | - Do not try to force them; bad things are supposed to happen, if done so.
51 | - Keep in mind that design patterns are solutions **to** problems, not solutions **finding** problems; so don't overthink.
52 | - If used in a correct place in a correct manner, they can prove to be a savior; or else they can result in a horrible mess of a code.
53 |
54 | > Also note that the code samples below are in PHP-7, however this shouldn't stop you because the concepts are same anyways.
55 |
56 | Types of Design Patterns
57 | -----------------
58 |
59 | * [Creational](#creational-design-patterns)
60 | * [Structural](#structural-design-patterns)
61 | * [Behavioral](#behavioral-design-patterns)
62 |
63 | Creational Design Patterns
64 | ==========================
65 |
66 | In plain words
67 | > Creational patterns are focused towards how to instantiate an object or group of related objects.
68 |
69 | Wikipedia says
70 | > 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.
71 |
72 | * [Simple Factory](#-simple-factory)
73 | * [Factory Method](#-factory-method)
74 | * [Abstract Factory](#-abstract-factory)
75 | * [Builder](#-builder)
76 | * [Prototype](#-prototype)
77 | * [Singleton](#-singleton)
78 |
79 | 🏠 Simple Factory
80 | --------------
81 | Real world example
82 | > 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.
83 |
84 | In plain words
85 | > Simple factory simply generates an instance for client without exposing any instantiation logic to the client
86 |
87 | Wikipedia says
88 | > 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".
89 |
90 | **Programmatic Example**
91 |
92 | First of all we have a door interface and the implementation
93 | ```php
94 | interface Door
95 | {
96 | public function getWidth(): float;
97 | public function getHeight(): float;
98 | }
99 |
100 | class WoodenDoor implements Door
101 | {
102 | protected $width;
103 | protected $height;
104 |
105 | public function __construct(float $width, float $height)
106 | {
107 | $this->width = $width;
108 | $this->height = $height;
109 | }
110 |
111 | public function getWidth(): float
112 | {
113 | return $this->width;
114 | }
115 |
116 | public function getHeight(): float
117 | {
118 | return $this->height;
119 | }
120 | }
121 | ```
122 | Then we have our door factory that makes the door and returns it
123 | ```php
124 | class DoorFactory
125 | {
126 | public static function makeDoor($width, $height): Door
127 | {
128 | return new WoodenDoor($width, $height);
129 | }
130 | }
131 | ```
132 | And then it can be used as
133 | ```php
134 | // Make me a door of 100x200
135 | $door = DoorFactory::makeDoor(100, 200);
136 |
137 | echo 'Width: ' . $door->getWidth();
138 | echo 'Height: ' . $door->getHeight();
139 |
140 | // Make me a door of 50x100
141 | $door2 = DoorFactory::makeDoor(50, 100);
142 | ```
143 |
144 | **When to Use?**
145 |
146 | 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.
147 |
148 | 🏭 Factory Method
149 | --------------
150 |
151 | Real world example
152 | > 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.
153 |
154 | In plain words
155 | > It provides a way to delegate the instantiation logic to child classes.
156 |
157 | Wikipedia says
158 | > 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.
159 |
160 | **Programmatic Example**
161 |
162 | Taking our hiring manager example above. First of all we have an interviewer interface and some implementations for it
163 |
164 | ```php
165 | interface Interviewer
166 | {
167 | public function askQuestions();
168 | }
169 |
170 | class Developer implements Interviewer
171 | {
172 | public function askQuestions()
173 | {
174 | echo 'Asking about design patterns!';
175 | }
176 | }
177 |
178 | class CommunityExecutive implements Interviewer
179 | {
180 | public function askQuestions()
181 | {
182 | echo 'Asking about community building';
183 | }
184 | }
185 | ```
186 |
187 | Now let us create our `HiringManager`
188 |
189 | ```php
190 | abstract class HiringManager
191 | {
192 |
193 | // Factory method
194 | abstract protected function makeInterviewer(): Interviewer;
195 |
196 | public function takeInterview()
197 | {
198 | $interviewer = $this->makeInterviewer();
199 | $interviewer->askQuestions();
200 | }
201 | }
202 |
203 | ```
204 | Now any child can extend it and provide the required interviewer
205 | ```php
206 | class DevelopmentManager extends HiringManager
207 | {
208 | protected function makeInterviewer(): Interviewer
209 | {
210 | return new Developer();
211 | }
212 | }
213 |
214 | class MarketingManager extends HiringManager
215 | {
216 | protected function makeInterviewer(): Interviewer
217 | {
218 | return new CommunityExecutive();
219 | }
220 | }
221 | ```
222 | and then it can be used as
223 |
224 | ```php
225 | $devManager = new DevelopmentManager();
226 | $devManager->takeInterview(); // Output: Asking about design patterns
227 |
228 | $marketingManager = new MarketingManager();
229 | $marketingManager->takeInterview(); // Output: Asking about community building.
230 | ```
231 |
232 | **When to use?**
233 |
234 | 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.
235 |
236 | 🔨 Abstract Factory
237 | ----------------
238 |
239 | Real world example
240 | > 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.
241 |
242 | In plain words
243 | > A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes.
244 |
245 | Wikipedia says
246 | > The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes
247 |
248 | **Programmatic Example**
249 |
250 | Translating the door example above. First of all we have our `Door` interface and some implementation for it
251 |
252 | ```php
253 | interface Door
254 | {
255 | public function getDescription();
256 | }
257 |
258 | class WoodenDoor implements Door
259 | {
260 | public function getDescription()
261 | {
262 | echo 'I am a wooden door';
263 | }
264 | }
265 |
266 | class IronDoor implements Door
267 | {
268 | public function getDescription()
269 | {
270 | echo 'I am an iron door';
271 | }
272 | }
273 | ```
274 | Then we have some fitting experts for each door type
275 |
276 | ```php
277 | interface DoorFittingExpert
278 | {
279 | public function getDescription();
280 | }
281 |
282 | class Welder implements DoorFittingExpert
283 | {
284 | public function getDescription()
285 | {
286 | echo 'I can only fit iron doors';
287 | }
288 | }
289 |
290 | class Carpenter implements DoorFittingExpert
291 | {
292 | public function getDescription()
293 | {
294 | echo 'I can only fit wooden doors';
295 | }
296 | }
297 | ```
298 |
299 | 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
300 | ```php
301 | interface DoorFactory
302 | {
303 | public function makeDoor(): Door;
304 | public function makeFittingExpert(): DoorFittingExpert;
305 | }
306 |
307 | // Wooden factory to return carpenter and wooden door
308 | class WoodenDoorFactory implements DoorFactory
309 | {
310 | public function makeDoor(): Door
311 | {
312 | return new WoodenDoor();
313 | }
314 |
315 | public function makeFittingExpert(): DoorFittingExpert
316 | {
317 | return new Carpenter();
318 | }
319 | }
320 |
321 | // Iron door factory to get iron door and the relevant fitting expert
322 | class IronDoorFactory implements DoorFactory
323 | {
324 | public function makeDoor(): Door
325 | {
326 | return new IronDoor();
327 | }
328 |
329 | public function makeFittingExpert(): DoorFittingExpert
330 | {
331 | return new Welder();
332 | }
333 | }
334 | ```
335 | And then it can be used as
336 | ```php
337 | $woodenFactory = new WoodenDoorFactory();
338 |
339 | $door = $woodenFactory->makeDoor();
340 | $expert = $woodenFactory->makeFittingExpert();
341 |
342 | $door->getDescription(); // Output: I am a wooden door
343 | $expert->getDescription(); // Output: I can only fit wooden doors
344 |
345 | // Same for Iron Factory
346 | $ironFactory = new IronDoorFactory();
347 |
348 | $door = $ironFactory->makeDoor();
349 | $expert = $ironFactory->makeFittingExpert();
350 |
351 | $door->getDescription(); // Output: I am an iron door
352 | $expert->getDescription(); // Output: I can only fit iron doors
353 | ```
354 |
355 | 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.
356 |
357 | **When to use?**
358 |
359 | When there are interrelated dependencies with not-that-simple creation logic involved
360 |
361 | 👷 Builder
362 | --------------------------------------------
363 | Real world example
364 | > 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.
365 |
366 | In plain words
367 | > 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.
368 |
369 | Wikipedia says
370 | > The builder pattern is an object creation software design pattern with the intentions of finding a solution to the telescoping constructor anti-pattern.
371 |
372 | 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:
373 |
374 | ```php
375 | public function __construct($size, $cheese = true, $pepperoni = true, $tomato = false, $lettuce = true)
376 | {
377 | }
378 | ```
379 |
380 | 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.
381 |
382 | **Programmatic Example**
383 |
384 | The sane alternative is to use the builder pattern. First of all we have our burger that we want to make
385 |
386 | ```php
387 | class Burger
388 | {
389 | protected $size;
390 |
391 | protected $cheese = false;
392 | protected $pepperoni = false;
393 | protected $lettuce = false;
394 | protected $tomato = false;
395 |
396 | public function __construct(BurgerBuilder $builder)
397 | {
398 | $this->size = $builder->size;
399 | $this->cheese = $builder->cheese;
400 | $this->pepperoni = $builder->pepperoni;
401 | $this->lettuce = $builder->lettuce;
402 | $this->tomato = $builder->tomato;
403 | }
404 | }
405 | ```
406 |
407 | And then we have the builder
408 |
409 | ```php
410 | class BurgerBuilder
411 | {
412 | public $size;
413 |
414 | public $cheese = false;
415 | public $pepperoni = false;
416 | public $lettuce = false;
417 | public $tomato = false;
418 |
419 | public function __construct(int $size)
420 | {
421 | $this->size = $size;
422 | }
423 |
424 | public function addPepperoni()
425 | {
426 | $this->pepperoni = true;
427 | return $this;
428 | }
429 |
430 | public function addLettuce()
431 | {
432 | $this->lettuce = true;
433 | return $this;
434 | }
435 |
436 | public function addCheese()
437 | {
438 | $this->cheese = true;
439 | return $this;
440 | }
441 |
442 | public function addTomato()
443 | {
444 | $this->tomato = true;
445 | return $this;
446 | }
447 |
448 | public function build(): Burger
449 | {
450 | return new Burger($this);
451 | }
452 | }
453 | ```
454 | And then it can be used as:
455 |
456 | ```php
457 | $burger = (new BurgerBuilder(14))
458 | ->addPepperoni()
459 | ->addLettuce()
460 | ->addTomato()
461 | ->build();
462 | ```
463 |
464 | **When to use?**
465 |
466 | 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.
467 |
468 | 🐑 Prototype
469 | ------------
470 | Real world example
471 | > 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
472 |
473 | In plain words
474 | > Create object based on an existing object through cloning.
475 |
476 | Wikipedia says
477 | > 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.
478 |
479 | 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.
480 |
481 | **Programmatic Example**
482 |
483 | In PHP, it can be easily done using `clone`
484 |
485 | ```php
486 | class Sheep
487 | {
488 | protected $name;
489 | protected $category;
490 |
491 | public function __construct(string $name, string $category = 'Mountain Sheep')
492 | {
493 | $this->name = $name;
494 | $this->category = $category;
495 | }
496 |
497 | public function setName(string $name)
498 | {
499 | $this->name = $name;
500 | }
501 |
502 | public function getName()
503 | {
504 | return $this->name;
505 | }
506 |
507 | public function setCategory(string $category)
508 | {
509 | $this->category = $category;
510 | }
511 |
512 | public function getCategory()
513 | {
514 | return $this->category;
515 | }
516 | }
517 | ```
518 | Then it can be cloned like below
519 | ```php
520 | $original = new Sheep('Jolly');
521 | echo $original->getName(); // Jolly
522 | echo $original->getCategory(); // Mountain Sheep
523 |
524 | // Clone and modify what is required
525 | $cloned = clone $original;
526 | $cloned->setName('Dolly');
527 | echo $cloned->getName(); // Dolly
528 | echo $cloned->getCategory(); // Mountain sheep
529 | ```
530 |
531 | Also you could use the magic method `__clone` to modify the cloning behavior.
532 |
533 | **When to use?**
534 |
535 | When an object is required that is similar to existing object or when the creation would be expensive as compared to cloning.
536 |
537 | 💍 Singleton
538 | ------------
539 | Real world example
540 | > 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.
541 |
542 | In plain words
543 | > Ensures that only one object of a particular class is ever created.
544 |
545 | Wikipedia says
546 | > 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.
547 |
548 | 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.
549 |
550 | **Programmatic Example**
551 |
552 | To create a singleton, make the constructor private, disable cloning, disable extension and create a static variable to house the instance
553 | ```php
554 | final class President
555 | {
556 | private static $instance;
557 |
558 | private function __construct()
559 | {
560 | // Hide the constructor
561 | }
562 |
563 | public static function getInstance(): President
564 | {
565 | if (!self::$instance) {
566 | self::$instance = new self();
567 | }
568 |
569 | return self::$instance;
570 | }
571 |
572 | private function __clone()
573 | {
574 | // Disable cloning
575 | }
576 |
577 | private function __wakeup()
578 | {
579 | // Disable unserialize
580 | }
581 | }
582 | ```
583 | Then in order to use
584 | ```php
585 | $president1 = President::getInstance();
586 | $president2 = President::getInstance();
587 |
588 | var_dump($president1 === $president2); // true
589 | ```
590 |
591 | Structural Design Patterns
592 | ==========================
593 | In plain words
594 | > 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?"
595 |
596 | Wikipedia says
597 | > In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.
598 |
599 | * [Adapter](#-adapter)
600 | * [Bridge](#-bridge)
601 | * [Composite](#-composite)
602 | * [Decorator](#-decorator)
603 | * [Facade](#-facade)
604 | * [Flyweight](#-flyweight)
605 | * [Proxy](#-proxy)
606 |
607 | 🔌 Adapter
608 | -------
609 | Real world example
610 | > 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.
611 | > 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.
612 | > Yet another example would be a translator translating words spoken by one person to another
613 |
614 | In plain words
615 | > Adapter pattern lets you wrap an otherwise incompatible object in an adapter to make it compatible with another class.
616 |
617 | Wikipedia says
618 | > 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.
619 |
620 | **Programmatic Example**
621 |
622 | Consider a game where there is a hunter and he hunts lions.
623 |
624 | First we have an interface `Lion` that all types of lions have to implement
625 |
626 | ```php
627 | interface Lion
628 | {
629 | public function roar();
630 | }
631 |
632 | class AfricanLion implements Lion
633 | {
634 | public function roar()
635 | {
636 | }
637 | }
638 |
639 | class AsianLion implements Lion
640 | {
641 | public function roar()
642 | {
643 | }
644 | }
645 | ```
646 | And hunter expects any implementation of `Lion` interface to hunt.
647 | ```php
648 | class Hunter
649 | {
650 | public function hunt(Lion $lion)
651 | {
652 | $lion->roar();
653 | }
654 | }
655 | ```
656 |
657 | 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
658 |
659 | ```php
660 | // This needs to be added to the game
661 | class WildDog
662 | {
663 | public function bark()
664 | {
665 | }
666 | }
667 |
668 | // Adapter around wild dog to make it compatible with our game
669 | class WildDogAdapter implements Lion
670 | {
671 | protected $dog;
672 |
673 | public function __construct(WildDog $dog)
674 | {
675 | $this->dog = $dog;
676 | }
677 |
678 | public function roar()
679 | {
680 | $this->dog->bark();
681 | }
682 | }
683 | ```
684 | And now the `WildDog` can be used in our game using `WildDogAdapter`.
685 |
686 | ```php
687 | $wildDog = new WildDog();
688 | $wildDogAdapter = new WildDogAdapter($wildDog);
689 |
690 | $hunter = new Hunter();
691 | $hunter->hunt($wildDogAdapter);
692 | ```
693 |
694 | 🚡 Bridge
695 | ------
696 | Real world example
697 | > 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.
698 |
699 | 
700 |
701 | In Plain Words
702 | > Bridge pattern is about preferring composition over inheritance. Implementation details are pushed from a hierarchy to another object with a separate hierarchy.
703 |
704 | Wikipedia says
705 | > 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"
706 |
707 | **Programmatic Example**
708 |
709 | Translating our WebPage example from above. Here we have the `WebPage` hierarchy
710 |
711 | ```php
712 | interface WebPage
713 | {
714 | public function __construct(Theme $theme);
715 | public function getContent();
716 | }
717 |
718 | class About implements WebPage
719 | {
720 | protected $theme;
721 |
722 | public function __construct(Theme $theme)
723 | {
724 | $this->theme = $theme;
725 | }
726 |
727 | public function getContent()
728 | {
729 | return "About page in " . $this->theme->getColor();
730 | }
731 | }
732 |
733 | class Careers implements WebPage
734 | {
735 | protected $theme;
736 |
737 | public function __construct(Theme $theme)
738 | {
739 | $this->theme = $theme;
740 | }
741 |
742 | public function getContent()
743 | {
744 | return "Careers page in " . $this->theme->getColor();
745 | }
746 | }
747 | ```
748 | And the separate theme hierarchy
749 | ```php
750 |
751 | interface Theme
752 | {
753 | public function getColor();
754 | }
755 |
756 | class DarkTheme implements Theme
757 | {
758 | public function getColor()
759 | {
760 | return 'Dark Black';
761 | }
762 | }
763 | class LightTheme implements Theme
764 | {
765 | public function getColor()
766 | {
767 | return 'Off white';
768 | }
769 | }
770 | class AquaTheme implements Theme
771 | {
772 | public function getColor()
773 | {
774 | return 'Light blue';
775 | }
776 | }
777 | ```
778 | And both the hierarchies
779 | ```php
780 | $darkTheme = new DarkTheme();
781 |
782 | $about = new About($darkTheme);
783 | $careers = new Careers($darkTheme);
784 |
785 | echo $about->getContent(); // "About page in Dark Black";
786 | echo $careers->getContent(); // "Careers page in Dark Black";
787 | ```
788 |
789 | 🌿 Composite
790 | -----------------
791 |
792 | Real world example
793 | > 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.
794 |
795 | In plain words
796 | > Composite pattern lets clients treat the individual objects in a uniform manner.
797 |
798 | Wikipedia says
799 | > 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.
800 |
801 | **Programmatic Example**
802 |
803 | Taking our employees example from above. Here we have different employee types
804 |
805 | ```php
806 | interface Employee
807 | {
808 | public function __construct(string $name, float $salary);
809 | public function getName(): string;
810 | public function setSalary(float $salary);
811 | public function getSalary(): float;
812 | public function getRoles(): array;
813 | }
814 |
815 | class Developer implements Employee
816 | {
817 | protected $salary;
818 | protected $name;
819 | protected $roles;
820 |
821 | public function __construct(string $name, float $salary)
822 | {
823 | $this->name = $name;
824 | $this->salary = $salary;
825 | }
826 |
827 | public function getName(): string
828 | {
829 | return $this->name;
830 | }
831 |
832 | public function setSalary(float $salary)
833 | {
834 | $this->salary = $salary;
835 | }
836 |
837 | public function getSalary(): float
838 | {
839 | return $this->salary;
840 | }
841 |
842 | public function getRoles(): array
843 | {
844 | return $this->roles;
845 | }
846 | }
847 |
848 | class Designer implements Employee
849 | {
850 | protected $salary;
851 | protected $name;
852 | protected $roles;
853 |
854 | public function __construct(string $name, float $salary)
855 | {
856 | $this->name = $name;
857 | $this->salary = $salary;
858 | }
859 |
860 | public function getName(): string
861 | {
862 | return $this->name;
863 | }
864 |
865 | public function setSalary(float $salary)
866 | {
867 | $this->salary = $salary;
868 | }
869 |
870 | public function getSalary(): float
871 | {
872 | return $this->salary;
873 | }
874 |
875 | public function getRoles(): array
876 | {
877 | return $this->roles;
878 | }
879 | }
880 | ```
881 |
882 | Then we have an organization which consists of several different types of employees
883 |
884 | ```php
885 | class Organization
886 | {
887 | protected $employees;
888 |
889 | public function addEmployee(Employee $employee)
890 | {
891 | $this->employees[] = $employee;
892 | }
893 |
894 | public function getNetSalaries(): float
895 | {
896 | $netSalary = 0;
897 |
898 | foreach ($this->employees as $employee) {
899 | $netSalary += $employee->getSalary();
900 | }
901 |
902 | return $netSalary;
903 | }
904 | }
905 | ```
906 |
907 | And then it can be used as
908 |
909 | ```php
910 | // Prepare the employees
911 | $john = new Developer('John Doe', 12000);
912 | $jane = new Designer('Jane Doe', 15000);
913 |
914 | // Add them to organization
915 | $organization = new Organization();
916 | $organization->addEmployee($john);
917 | $organization->addEmployee($jane);
918 |
919 | echo "Net salaries: " . $organization->getNetSalaries(); // Net Salaries: 27000
920 | ```
921 |
922 | ☕ Decorator
923 | -------------
924 |
925 | Real world example
926 |
927 | > 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.
928 |
929 | In plain words
930 | > Decorator pattern lets you dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class.
931 |
932 | Wikipedia says
933 | > 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.
934 |
935 | **Programmatic Example**
936 |
937 | Lets take coffee for example. First of all we have a simple coffee implementing the coffee interface
938 |
939 | ```php
940 | interface Coffee
941 | {
942 | public function getCost();
943 | public function getDescription();
944 | }
945 |
946 | class SimpleCoffee implements Coffee
947 | {
948 | public function getCost()
949 | {
950 | return 10;
951 | }
952 |
953 | public function getDescription()
954 | {
955 | return 'Simple coffee';
956 | }
957 | }
958 | ```
959 | We want to make the code extensible to allow options to modify it if required. Lets make some add-ons (decorators)
960 | ```php
961 | class MilkCoffee implements Coffee
962 | {
963 | protected $coffee;
964 |
965 | public function __construct(Coffee $coffee)
966 | {
967 | $this->coffee = $coffee;
968 | }
969 |
970 | public function getCost()
971 | {
972 | return $this->coffee->getCost() + 2;
973 | }
974 |
975 | public function getDescription()
976 | {
977 | return $this->coffee->getDescription() . ', milk';
978 | }
979 | }
980 |
981 | class WhipCoffee implements Coffee
982 | {
983 | protected $coffee;
984 |
985 | public function __construct(Coffee $coffee)
986 | {
987 | $this->coffee = $coffee;
988 | }
989 |
990 | public function getCost()
991 | {
992 | return $this->coffee->getCost() + 5;
993 | }
994 |
995 | public function getDescription()
996 | {
997 | return $this->coffee->getDescription() . ', whip';
998 | }
999 | }
1000 |
1001 | class VanillaCoffee implements Coffee
1002 | {
1003 | protected $coffee;
1004 |
1005 | public function __construct(Coffee $coffee)
1006 | {
1007 | $this->coffee = $coffee;
1008 | }
1009 |
1010 | public function getCost()
1011 | {
1012 | return $this->coffee->getCost() + 3;
1013 | }
1014 |
1015 | public function getDescription()
1016 | {
1017 | return $this->coffee->getDescription() . ', vanilla';
1018 | }
1019 | }
1020 | ```
1021 |
1022 | Lets make a coffee now
1023 |
1024 | ```php
1025 | $someCoffee = new SimpleCoffee();
1026 | echo $someCoffee->getCost(); // 10
1027 | echo $someCoffee->getDescription(); // Simple Coffee
1028 |
1029 | $someCoffee = new MilkCoffee($someCoffee);
1030 | echo $someCoffee->getCost(); // 12
1031 | echo $someCoffee->getDescription(); // Simple Coffee, milk
1032 |
1033 | $someCoffee = new WhipCoffee($someCoffee);
1034 | echo $someCoffee->getCost(); // 17
1035 | echo $someCoffee->getDescription(); // Simple Coffee, milk, whip
1036 |
1037 | $someCoffee = new VanillaCoffee($someCoffee);
1038 | echo $someCoffee->getCost(); // 20
1039 | echo $someCoffee->getDescription(); // Simple Coffee, milk, whip, vanilla
1040 | ```
1041 |
1042 | 📦 Facade
1043 | ----------------
1044 |
1045 | Real world example
1046 | > 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.
1047 |
1048 | In plain words
1049 | > Facade pattern provides a simplified interface to a complex subsystem.
1050 |
1051 | Wikipedia says
1052 | > A facade is an object that provides a simplified interface to a larger body of code, such as a class library.
1053 |
1054 | **Programmatic Example**
1055 |
1056 | Taking our computer example from above. Here we have the computer class
1057 |
1058 | ```php
1059 | class Computer
1060 | {
1061 | public function getElectricShock()
1062 | {
1063 | echo "Ouch!";
1064 | }
1065 |
1066 | public function makeSound()
1067 | {
1068 | echo "Beep beep!";
1069 | }
1070 |
1071 | public function showLoadingScreen()
1072 | {
1073 | echo "Loading..";
1074 | }
1075 |
1076 | public function bam()
1077 | {
1078 | echo "Ready to be used!";
1079 | }
1080 |
1081 | public function closeEverything()
1082 | {
1083 | echo "Bup bup bup buzzzz!";
1084 | }
1085 |
1086 | public function sooth()
1087 | {
1088 | echo "Zzzzz";
1089 | }
1090 |
1091 | public function pullCurrent()
1092 | {
1093 | echo "Haaah!";
1094 | }
1095 | }
1096 | ```
1097 | Here we have the facade
1098 | ```php
1099 | class ComputerFacade
1100 | {
1101 | protected $computer;
1102 |
1103 | public function __construct(Computer $computer)
1104 | {
1105 | $this->computer = $computer;
1106 | }
1107 |
1108 | public function turnOn()
1109 | {
1110 | $this->computer->getElectricShock();
1111 | $this->computer->makeSound();
1112 | $this->computer->showLoadingScreen();
1113 | $this->computer->bam();
1114 | }
1115 |
1116 | public function turnOff()
1117 | {
1118 | $this->computer->closeEverything();
1119 | $this->computer->pullCurrent();
1120 | $this->computer->sooth();
1121 | }
1122 | }
1123 | ```
1124 | Now to use the facade
1125 | ```php
1126 | $computer = new ComputerFacade(new Computer());
1127 | $computer->turnOn(); // Ouch! Beep beep! Loading.. Ready to be used!
1128 | $computer->turnOff(); // Bup bup buzzz! Haah! Zzzzz
1129 | ```
1130 |
1131 | 🍃 Flyweight
1132 | ---------
1133 |
1134 | Real world example
1135 | > 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.
1136 |
1137 | In plain words
1138 | > It is used to minimize memory usage or computational expenses by sharing as much as possible with similar objects.
1139 |
1140 | Wikipedia says
1141 | > 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.
1142 |
1143 | **Programmatic example**
1144 |
1145 | Translating our tea example from above. First of all we have tea types and tea maker
1146 |
1147 | ```php
1148 | // Anything that will be cached is flyweight.
1149 | // Types of tea here will be flyweights.
1150 | class KarakTea
1151 | {
1152 | }
1153 |
1154 | // Acts as a factory and saves the tea
1155 | class TeaMaker
1156 | {
1157 | protected $availableTea = [];
1158 |
1159 | public function make($preference)
1160 | {
1161 | if (empty($this->availableTea[$preference])) {
1162 | $this->availableTea[$preference] = new KarakTea();
1163 | }
1164 |
1165 | return $this->availableTea[$preference];
1166 | }
1167 | }
1168 | ```
1169 |
1170 | Then we have the `TeaShop` which takes orders and serves them
1171 |
1172 | ```php
1173 | class TeaShop
1174 | {
1175 | protected $orders;
1176 | protected $teaMaker;
1177 |
1178 | public function __construct(TeaMaker $teaMaker)
1179 | {
1180 | $this->teaMaker = $teaMaker;
1181 | }
1182 |
1183 | public function takeOrder(string $teaType, int $table)
1184 | {
1185 | $this->orders[$table] = $this->teaMaker->make($teaType);
1186 | }
1187 |
1188 | public function serve()
1189 | {
1190 | foreach ($this->orders as $table => $tea) {
1191 | echo "Serving tea to table# " . $table;
1192 | }
1193 | }
1194 | }
1195 | ```
1196 | And it can be used as below
1197 |
1198 | ```php
1199 | $teaMaker = new TeaMaker();
1200 | $shop = new TeaShop($teaMaker);
1201 |
1202 | $shop->takeOrder('less sugar', 1);
1203 | $shop->takeOrder('more milk', 2);
1204 | $shop->takeOrder('without sugar', 5);
1205 |
1206 | $shop->serve();
1207 | // Serving tea to table# 1
1208 | // Serving tea to table# 2
1209 | // Serving tea to table# 5
1210 | ```
1211 |
1212 | 🎱 Proxy
1213 | -------------------
1214 | Real world example
1215 | > 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.
1216 |
1217 | In plain words
1218 | > Using the proxy pattern, a class represents the functionality of another class.
1219 |
1220 | Wikipedia says
1221 | > 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.
1222 |
1223 | **Programmatic Example**
1224 |
1225 | Taking our security door example from above. Firstly we have the door interface and an implementation of door
1226 |
1227 | ```php
1228 | interface Door
1229 | {
1230 | public function open();
1231 | public function close();
1232 | }
1233 |
1234 | class LabDoor implements Door
1235 | {
1236 | public function open()
1237 | {
1238 | echo "Opening lab door";
1239 | }
1240 |
1241 | public function close()
1242 | {
1243 | echo "Closing the lab door";
1244 | }
1245 | }
1246 | ```
1247 | Then we have a proxy to secure any doors that we want
1248 | ```php
1249 | class SecuredDoor implements Door
1250 | {
1251 | protected $door;
1252 |
1253 | public function __construct(Door $door)
1254 | {
1255 | $this->door = $door;
1256 | }
1257 |
1258 | public function open($password)
1259 | {
1260 | if ($this->authenticate($password)) {
1261 | $this->door->open();
1262 | } else {
1263 | echo "Big no! It ain't possible.";
1264 | }
1265 | }
1266 |
1267 | public function authenticate($password)
1268 | {
1269 | return $password === '$ecr@t';
1270 | }
1271 |
1272 | public function close()
1273 | {
1274 | $this->door->close();
1275 | }
1276 | }
1277 | ```
1278 | And here is how it can be used
1279 | ```php
1280 | $door = new SecuredDoor(new LabDoor());
1281 | $door->open('invalid'); // Big no! It ain't possible.
1282 |
1283 | $door->open('$ecr@t'); // Opening lab door
1284 | $door->close(); // Closing lab door
1285 | ```
1286 | 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`.
1287 |
1288 | Behavioral Design Patterns
1289 | ==========================
1290 |
1291 | In plain words
1292 | > It is concerned with assignment of responsibilities between the objects. What makes them different from structural patterns is they don't just specify the structure but also outline the patterns for message passing/communication between them. Or in other words, they assist in answering "How to run a behavior in software component?"
1293 |
1294 | Wikipedia says
1295 | > In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.
1296 |
1297 | * [Chain of Responsibility](#-chain-of-responsibility)
1298 | * [Command](#-command)
1299 | * [Iterator](#-iterator)
1300 | * [Mediator](#-mediator)
1301 | * [Memento](#-memento)
1302 | * [Observer](#-observer)
1303 | * [Visitor](#-visitor)
1304 | * [Strategy](#-strategy)
1305 | * [State](#-state)
1306 | * [Template Method](#-template-method)
1307 |
1308 | 🔗 Chain of Responsibility
1309 | -----------------------
1310 |
1311 | Real world example
1312 | > For example, you have three payment methods (`A`, `B` and `C`) setup in your account; each having a different amount in it. `A` has 100 USD, `B` has 300 USD and `C` having 1000 USD and the preference for payments is chosen as `A` then `B` then `C`. You try to purchase something that is worth 210 USD. Using Chain of Responsibility, first of all account `A` will be checked if it can make the purchase, if yes purchase will be made and the chain will be broken. If not, request will move forward to account `B` checking for amount if yes chain will be broken otherwise the request will keep forwarding till it finds the suitable handler. Here `A`, `B` and `C` are links of the chain and the whole phenomenon is Chain of Responsibility.
1313 |
1314 | In plain words
1315 | > It helps building a chain of objects. Request enters from one end and keeps going from object to object till it finds the suitable handler.
1316 |
1317 | Wikipedia says
1318 | > In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain.
1319 |
1320 | **Programmatic Example**
1321 |
1322 | Translating our account example above. First of all we have a base account having the logic for chaining the accounts together and some accounts
1323 |
1324 | ```php
1325 | abstract class Account
1326 | {
1327 | protected $successor;
1328 | protected $balance;
1329 |
1330 | public function setNext(Account $account)
1331 | {
1332 | $this->successor = $account;
1333 | }
1334 |
1335 | public function pay(float $amountToPay)
1336 | {
1337 | if ($this->canPay($amountToPay)) {
1338 | echo sprintf('Paid %s using %s' . PHP_EOL, $amountToPay, get_called_class());
1339 | } elseif ($this->successor) {
1340 | echo sprintf('Cannot pay using %s. Proceeding ..' . PHP_EOL, get_called_class());
1341 | $this->successor->pay($amountToPay);
1342 | } else {
1343 | throw new Exception('None of the accounts have enough balance');
1344 | }
1345 | }
1346 |
1347 | public function canPay($amount): bool
1348 | {
1349 | return $this->balance >= $amount;
1350 | }
1351 | }
1352 |
1353 | class Bank extends Account
1354 | {
1355 | protected $balance;
1356 |
1357 | public function __construct(float $balance)
1358 | {
1359 | $this->balance = $balance;
1360 | }
1361 | }
1362 |
1363 | class Paypal extends Account
1364 | {
1365 | protected $balance;
1366 |
1367 | public function __construct(float $balance)
1368 | {
1369 | $this->balance = $balance;
1370 | }
1371 | }
1372 |
1373 | class Bitcoin extends Account
1374 | {
1375 | protected $balance;
1376 |
1377 | public function __construct(float $balance)
1378 | {
1379 | $this->balance = $balance;
1380 | }
1381 | }
1382 | ```
1383 |
1384 | Now let's prepare the chain using the links defined above (i.e. Bank, Paypal, Bitcoin)
1385 |
1386 | ```php
1387 | // Let's prepare a chain like below
1388 | // $bank->$paypal->$bitcoin
1389 | //
1390 | // First priority bank
1391 | // If bank can't pay then paypal
1392 | // If paypal can't pay then bit coin
1393 |
1394 | $bank = new Bank(100); // Bank with balance 100
1395 | $paypal = new Paypal(200); // Paypal with balance 200
1396 | $bitcoin = new Bitcoin(300); // Bitcoin with balance 300
1397 |
1398 | $bank->setNext($paypal);
1399 | $paypal->setNext($bitcoin);
1400 |
1401 | // Let's try to pay using the first priority i.e. bank
1402 | $bank->pay(259);
1403 |
1404 | // Output will be
1405 | // ==============
1406 | // Cannot pay using bank. Proceeding ..
1407 | // Cannot pay using paypal. Proceeding ..:
1408 | // Paid 259 using Bitcoin!
1409 | ```
1410 |
1411 | 👮 Command
1412 | -------
1413 |
1414 | Real world example
1415 | > A generic example would be you ordering food at a restaurant. You (i.e. `Client`) ask the waiter (i.e. `Invoker`) to bring some food (i.e. `Command`) and waiter simply forwards the request to Chef (i.e. `Receiver`) who has the knowledge of what and how to cook.
1416 | > Another example would be you (i.e. `Client`) switching on (i.e. `Command`) the television (i.e. `Receiver`) using a remote control (`Invoker`).
1417 |
1418 | In plain words
1419 | > Allows you to encapsulate actions in objects. The key idea behind this pattern is to provide the means to decouple client from receiver.
1420 |
1421 | Wikipedia says
1422 | > In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.
1423 |
1424 | **Programmatic Example**
1425 |
1426 | First of all we have the receiver that has the implementation of every action that could be performed
1427 | ```php
1428 | // Receiver
1429 | class Bulb
1430 | {
1431 | public function turnOn()
1432 | {
1433 | echo "Bulb has been lit";
1434 | }
1435 |
1436 | public function turnOff()
1437 | {
1438 | echo "Darkness!";
1439 | }
1440 | }
1441 | ```
1442 | then we have an interface that each of the commands are going to implement and then we have a set of commands
1443 | ```php
1444 | interface Command
1445 | {
1446 | public function execute();
1447 | public function undo();
1448 | public function redo();
1449 | }
1450 |
1451 | // Command
1452 | class TurnOn implements Command
1453 | {
1454 | protected $bulb;
1455 |
1456 | public function __construct(Bulb $bulb)
1457 | {
1458 | $this->bulb = $bulb;
1459 | }
1460 |
1461 | public function execute()
1462 | {
1463 | $this->bulb->turnOn();
1464 | }
1465 |
1466 | public function undo()
1467 | {
1468 | $this->bulb->turnOff();
1469 | }
1470 |
1471 | public function redo()
1472 | {
1473 | $this->execute();
1474 | }
1475 | }
1476 |
1477 | class TurnOff implements Command
1478 | {
1479 | protected $bulb;
1480 |
1481 | public function __construct(Bulb $bulb)
1482 | {
1483 | $this->bulb = $bulb;
1484 | }
1485 |
1486 | public function execute()
1487 | {
1488 | $this->bulb->turnOff();
1489 | }
1490 |
1491 | public function undo()
1492 | {
1493 | $this->bulb->turnOn();
1494 | }
1495 |
1496 | public function redo()
1497 | {
1498 | $this->execute();
1499 | }
1500 | }
1501 | ```
1502 | Then we have an `Invoker` with whom the client will interact to process any commands
1503 | ```php
1504 | // Invoker
1505 | class RemoteControl
1506 | {
1507 | public function submit(Command $command)
1508 | {
1509 | $command->execute();
1510 | }
1511 | }
1512 | ```
1513 | Finally let's see how we can use it in our client
1514 | ```php
1515 | $bulb = new Bulb();
1516 |
1517 | $turnOn = new TurnOn($bulb);
1518 | $turnOff = new TurnOff($bulb);
1519 |
1520 | $remote = new RemoteControl();
1521 | $remote->submit($turnOn); // Bulb has been lit!
1522 | $remote->submit($turnOff); // Darkness!
1523 | ```
1524 |
1525 | Command pattern can also be used to implement a transaction based system. Where you keep maintaining the history of commands as soon as you execute them. If the final command is successfully executed, all good otherwise just iterate through the history and keep executing the `undo` on all the executed commands.
1526 |
1527 | ➿ Iterator
1528 | --------
1529 |
1530 | Real world example
1531 | > An old radio set will be a good example of iterator, where user could start at some channel and then use next or previous buttons to go through the respective channels. Or take an example of MP3 player or a TV set where you could press the next and previous buttons to go through the consecutive channels or in other words they all provide an interface to iterate through the respective channels, songs or radio stations.
1532 |
1533 | In plain words
1534 | > It presents a way to access the elements of an object without exposing the underlying presentation.
1535 |
1536 | Wikipedia says
1537 | > In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.
1538 |
1539 | **Programmatic example**
1540 |
1541 | In PHP it is quite easy to implement using SPL (Standard PHP Library). Translating our radio stations example from above. First of all we have `RadioStation`
1542 |
1543 | ```php
1544 | class RadioStation
1545 | {
1546 | protected $frequency;
1547 |
1548 | public function __construct(float $frequency)
1549 | {
1550 | $this->frequency = $frequency;
1551 | }
1552 |
1553 | public function getFrequency(): float
1554 | {
1555 | return $this->frequency;
1556 | }
1557 | }
1558 | ```
1559 | Then we have our iterator
1560 |
1561 | ```php
1562 | use Countable;
1563 | use Iterator;
1564 |
1565 | class StationList implements Countable, Iterator
1566 | {
1567 | /** @var RadioStation[] $stations */
1568 | protected $stations = [];
1569 |
1570 | /** @var int $counter */
1571 | protected $counter;
1572 |
1573 | public function addStation(RadioStation $station)
1574 | {
1575 | $this->stations[] = $station;
1576 | }
1577 |
1578 | public function removeStation(RadioStation $toRemove)
1579 | {
1580 | $toRemoveFrequency = $toRemove->getFrequency();
1581 | $this->stations = array_filter($this->stations, function (RadioStation $station) use ($toRemoveFrequency) {
1582 | return $station->getFrequency() !== $toRemoveFrequency;
1583 | });
1584 | }
1585 |
1586 | public function count(): int
1587 | {
1588 | return count($this->stations);
1589 | }
1590 |
1591 | public function current(): RadioStation
1592 | {
1593 | return $this->stations[$this->counter];
1594 | }
1595 |
1596 | public function key()
1597 | {
1598 | return $this->counter;
1599 | }
1600 |
1601 | public function next()
1602 | {
1603 | $this->counter++;
1604 | }
1605 |
1606 | public function rewind()
1607 | {
1608 | $this->counter = 0;
1609 | }
1610 |
1611 | public function valid(): bool
1612 | {
1613 | return isset($this->stations[$this->counter]);
1614 | }
1615 | }
1616 | ```
1617 | And then it can be used as
1618 | ```php
1619 | $stationList = new StationList();
1620 |
1621 | $stationList->addStation(new RadioStation(89));
1622 | $stationList->addStation(new RadioStation(101));
1623 | $stationList->addStation(new RadioStation(102));
1624 | $stationList->addStation(new RadioStation(103.2));
1625 |
1626 | foreach($stationList as $station) {
1627 | echo $station->getFrequency() . PHP_EOL;
1628 | }
1629 |
1630 | $stationList->removeStation(new RadioStation(89)); // Will remove station 89
1631 | ```
1632 |
1633 | 👽 Mediator
1634 | ========
1635 |
1636 | Real world example
1637 | > 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.
1638 |
1639 | In plain words
1640 | > 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.
1641 |
1642 | Wikipedia says
1643 | > 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.
1644 |
1645 | **Programmatic Example**
1646 |
1647 | Here is the simplest example of a chat room (i.e. mediator) with users (i.e. colleagues) sending messages to each other.
1648 |
1649 | First of all, we have the mediator i.e. the chat room
1650 |
1651 | ```php
1652 | interface ChatRoomMediator
1653 | {
1654 | public function showMessage(User $user, string $message);
1655 | }
1656 |
1657 | // Mediator
1658 | class ChatRoom implements ChatRoomMediator
1659 | {
1660 | public function showMessage(User $user, string $message)
1661 | {
1662 | $time = date('M d, y H:i');
1663 | $sender = $user->getName();
1664 |
1665 | echo $time . '[' . $sender . ']:' . $message;
1666 | }
1667 | }
1668 | ```
1669 |
1670 | Then we have our users i.e. colleagues
1671 | ```php
1672 | class User {
1673 | protected $name;
1674 | protected $chatMediator;
1675 |
1676 | public function __construct(string $name, ChatRoomMediator $chatMediator) {
1677 | $this->name = $name;
1678 | $this->chatMediator = $chatMediator;
1679 | }
1680 |
1681 | public function getName() {
1682 | return $this->name;
1683 | }
1684 |
1685 | public function send($message) {
1686 | $this->chatMediator->showMessage($this, $message);
1687 | }
1688 | }
1689 | ```
1690 | And the usage
1691 | ```php
1692 | $mediator = new ChatRoom();
1693 |
1694 | $john = new User('John Doe', $mediator);
1695 | $jane = new User('Jane Doe', $mediator);
1696 |
1697 | $john->send('Hi there!');
1698 | $jane->send('Hey!');
1699 |
1700 | // Output will be
1701 | // Feb 14, 10:58 [John]: Hi there!
1702 | // Feb 14, 10:58 [Jane]: Hey!
1703 | ```
1704 |
1705 | 💾 Memento
1706 | -------
1707 | Real world example
1708 | > 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).
1709 |
1710 | In plain words
1711 | > 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.
1712 |
1713 | Wikipedia says
1714 | > The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).
1715 |
1716 | Usually useful when you need to provide some sort of undo functionality.
1717 |
1718 | **Programmatic Example**
1719 |
1720 | Lets take an example of text editor which keeps saving the state from time to time and that you can restore if you want.
1721 |
1722 | First of all we have our memento object that will be able to hold the editor state
1723 |
1724 | ```php
1725 | class EditorMemento
1726 | {
1727 | protected $content;
1728 |
1729 | public function __construct(string $content)
1730 | {
1731 | $this->content = $content;
1732 | }
1733 |
1734 | public function getContent()
1735 | {
1736 | return $this->content;
1737 | }
1738 | }
1739 | ```
1740 |
1741 | Then we have our editor i.e. originator that is going to use memento object
1742 |
1743 | ```php
1744 | class Editor
1745 | {
1746 | protected $content = '';
1747 |
1748 | public function type(string $words)
1749 | {
1750 | $this->content = $this->content . ' ' . $words;
1751 | }
1752 |
1753 | public function getContent()
1754 | {
1755 | return $this->content;
1756 | }
1757 |
1758 | public function save()
1759 | {
1760 | return new EditorMemento($this->content);
1761 | }
1762 |
1763 | public function restore(EditorMemento $memento)
1764 | {
1765 | $this->content = $memento->getContent();
1766 | }
1767 | }
1768 | ```
1769 |
1770 | And then it can be used as
1771 |
1772 | ```php
1773 | $editor = new Editor();
1774 |
1775 | // Type some stuff
1776 | $editor->type('This is the first sentence.');
1777 | $editor->type('This is second.');
1778 |
1779 | // Save the state to restore to : This is the first sentence. This is second.
1780 | $saved = $editor->save();
1781 |
1782 | // Type some more
1783 | $editor->type('And this is third.');
1784 |
1785 | // Output: Content before Saving
1786 | echo $editor->getContent(); // This is the first sentence. This is second. And this is third.
1787 |
1788 | // Restoring to last saved state
1789 | $editor->restore($saved);
1790 |
1791 | $editor->getContent(); // This is the first sentence. This is second.
1792 | ```
1793 |
1794 | 😎 Observer
1795 | --------
1796 | Real world example
1797 | > 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.
1798 |
1799 | In plain words
1800 | > Defines a dependency between objects so that whenever an object changes its state, all its dependents are notified.
1801 |
1802 | Wikipedia says
1803 | > 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.
1804 |
1805 | **Programmatic example**
1806 |
1807 | Translating our example from above. First of all we have job seekers that need to be notified for a job posting
1808 | ```php
1809 | class JobPost
1810 | {
1811 | protected $title;
1812 |
1813 | public function __construct(string $title)
1814 | {
1815 | $this->title = $title;
1816 | }
1817 |
1818 | public function getTitle()
1819 | {
1820 | return $this->title;
1821 | }
1822 | }
1823 |
1824 | class JobSeeker implements Observer
1825 | {
1826 | protected $name;
1827 |
1828 | public function __construct(string $name)
1829 | {
1830 | $this->name = $name;
1831 | }
1832 |
1833 | public function onJobPosted(JobPost $job)
1834 | {
1835 | // Do something with the job posting
1836 | echo 'Hi ' . $this->name . '! New job posted: '. $job->getTitle();
1837 | }
1838 | }
1839 | ```
1840 | Then we have our job postings to which the job seekers will subscribe
1841 | ```php
1842 | class EmploymentAgency implements Observable
1843 | {
1844 | protected $observers = [];
1845 |
1846 | protected function notify(JobPost $jobPosting)
1847 | {
1848 | foreach ($this->observers as $observer) {
1849 | $observer->onJobPosted($jobPosting);
1850 | }
1851 | }
1852 |
1853 | public function attach(Observer $observer)
1854 | {
1855 | $this->observers[] = $observer;
1856 | }
1857 |
1858 | public function addJob(JobPost $jobPosting)
1859 | {
1860 | $this->notify($jobPosting);
1861 | }
1862 | }
1863 | ```
1864 | Then it can be used as
1865 | ```php
1866 | // Create subscribers
1867 | $johnDoe = new JobSeeker('John Doe');
1868 | $janeDoe = new JobSeeker('Jane Doe');
1869 |
1870 | // Create publisher and attach subscribers
1871 | $jobPostings = new EmploymentAgency();
1872 | $jobPostings->attach($johnDoe);
1873 | $jobPostings->attach($janeDoe);
1874 |
1875 | // Add a new job and see if subscribers get notified
1876 | $jobPostings->addJob(new JobPost('Software Engineer'));
1877 |
1878 | // Output
1879 | // Hi John Doe! New job posted: Software Engineer
1880 | // Hi Jane Doe! New job posted: Software Engineer
1881 | ```
1882 |
1883 | 🏃 Visitor
1884 | -------
1885 | Real world example
1886 | > 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.
1887 |
1888 | In plain words
1889 | > Visitor pattern lets you add further operations to objects without having to modify them.
1890 |
1891 | Wikipedia says
1892 | > 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.
1893 |
1894 | **Programmatic example**
1895 |
1896 | 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
1897 |
1898 | ```php
1899 | // Visitee
1900 | interface Animal
1901 | {
1902 | public function accept(AnimalOperation $operation);
1903 | }
1904 |
1905 | // Visitor
1906 | interface AnimalOperation
1907 | {
1908 | public function visitMonkey(Monkey $monkey);
1909 | public function visitLion(Lion $lion);
1910 | public function visitDolphin(Dolphin $dolphin);
1911 | }
1912 | ```
1913 | Then we have our implementations for the animals
1914 | ```php
1915 | class Monkey implements Animal
1916 | {
1917 | public function shout()
1918 | {
1919 | echo 'Ooh oo aa aa!';
1920 | }
1921 |
1922 | public function accept(AnimalOperation $operation)
1923 | {
1924 | $operation->visitMonkey($this);
1925 | }
1926 | }
1927 |
1928 | class Lion implements Animal
1929 | {
1930 | public function roar()
1931 | {
1932 | echo 'Roaaar!';
1933 | }
1934 |
1935 | public function accept(AnimalOperation $operation)
1936 | {
1937 | $operation->visitLion($this);
1938 | }
1939 | }
1940 |
1941 | class Dolphin implements Animal
1942 | {
1943 | public function speak()
1944 | {
1945 | echo 'Tuut tuttu tuutt!';
1946 | }
1947 |
1948 | public function accept(AnimalOperation $operation)
1949 | {
1950 | $operation->visitDolphin($this);
1951 | }
1952 | }
1953 | ```
1954 | Let's implement our visitor
1955 | ```php
1956 | class Speak implements AnimalOperation
1957 | {
1958 | public function visitMonkey(Monkey $monkey)
1959 | {
1960 | $monkey->shout();
1961 | }
1962 |
1963 | public function visitLion(Lion $lion)
1964 | {
1965 | $lion->roar();
1966 | }
1967 |
1968 | public function visitDolphin(Dolphin $dolphin)
1969 | {
1970 | $dolphin->speak();
1971 | }
1972 | }
1973 | ```
1974 |
1975 | And then it can be used as
1976 | ```php
1977 | $monkey = new Monkey();
1978 | $lion = new Lion();
1979 | $dolphin = new Dolphin();
1980 |
1981 | $speak = new Speak();
1982 |
1983 | $monkey->accept($speak); // Ooh oo aa aa!
1984 | $lion->accept($speak); // Roaaar!
1985 | $dolphin->accept($speak); // Tuut tutt tuutt!
1986 | ```
1987 | 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.
1988 |
1989 | ```php
1990 | class Jump implements AnimalOperation
1991 | {
1992 | public function visitMonkey(Monkey $monkey)
1993 | {
1994 | echo 'Jumped 20 feet high! on to the tree!';
1995 | }
1996 |
1997 | public function visitLion(Lion $lion)
1998 | {
1999 | echo 'Jumped 7 feet! Back on the ground!';
2000 | }
2001 |
2002 | public function visitDolphin(Dolphin $dolphin)
2003 | {
2004 | echo 'Walked on water a little and disappeared';
2005 | }
2006 | }
2007 | ```
2008 | And for the usage
2009 | ```php
2010 | $jump = new Jump();
2011 |
2012 | $monkey->accept($speak); // Ooh oo aa aa!
2013 | $monkey->accept($jump); // Jumped 20 feet high! on to the tree!
2014 |
2015 | $lion->accept($speak); // Roaaar!
2016 | $lion->accept($jump); // Jumped 7 feet! Back on the ground!
2017 |
2018 | $dolphin->accept($speak); // Tuut tutt tuutt!
2019 | $dolphin->accept($jump); // Walked on water a little and disappeared
2020 | ```
2021 |
2022 | 💡 Strategy
2023 | --------
2024 |
2025 | Real world example
2026 | > 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.
2027 |
2028 | In plain words
2029 | > Strategy pattern allows you to switch the algorithm or strategy based upon the situation.
2030 |
2031 | Wikipedia says
2032 | > 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.
2033 |
2034 | **Programmatic example**
2035 |
2036 | Translating our example from above. First of all we have our strategy interface and different strategy implementations
2037 |
2038 | ```php
2039 | interface SortStrategy
2040 | {
2041 | public function sort(array $dataset): array;
2042 | }
2043 |
2044 | class BubbleSortStrategy implements SortStrategy
2045 | {
2046 | public function sort(array $dataset): array
2047 | {
2048 | echo "Sorting using bubble sort";
2049 |
2050 | // Do sorting
2051 | return $dataset;
2052 | }
2053 | }
2054 |
2055 | class QuickSortStrategy implements SortStrategy
2056 | {
2057 | public function sort(array $dataset): array
2058 | {
2059 | echo "Sorting using quick sort";
2060 |
2061 | // Do sorting
2062 | return $dataset;
2063 | }
2064 | }
2065 | ```
2066 |
2067 | And then we have our client that is going to use any strategy
2068 | ```php
2069 | class Sorter
2070 | {
2071 | protected $sorterSmall;
2072 | protected $sorterBig;
2073 |
2074 | public function __construct(SortStrategy $sorterSmall, SortStrategy $sorterBig)
2075 | {
2076 | $this->sorterSmall = $sorterSmall;
2077 | $this->sorterBig = $sorterBig;
2078 | }
2079 |
2080 | public function sort(array $dataset): array
2081 | {
2082 | if (count($dataset) > 5) {
2083 | return $this->sorterBig->sort($dataset);
2084 | } else {
2085 | return $this->sorterSmall->sort($dataset);
2086 | }
2087 | }
2088 | }
2089 | ```
2090 | And it can be used as
2091 | ```php
2092 | $smalldataset = [1, 3, 4, 2];
2093 | $bigdataset = [1, 4, 3, 2, 8, 10, 5, 6, 9, 7];
2094 |
2095 | $sorter = new Sorter(new BubbleSortStrategy(), new QuickSortStrategy());
2096 |
2097 | $sorter->sort($dataset); // Output : Sorting using bubble sort
2098 |
2099 | $sorter->sort($bigdataset); // Output : Sorting using quick sort
2100 | ```
2101 |
2102 | 💢 State
2103 | -----
2104 | Real world example
2105 | > 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.
2106 |
2107 | In plain words
2108 | > It lets you change the behavior of a class when the state changes.
2109 |
2110 | Wikipedia says
2111 | > 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.
2112 | > 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.
2113 |
2114 | **Programmatic example**
2115 |
2116 | Let's take an example of a phone. First of all we have our state interface and some state implementations
2117 |
2118 | ```php
2119 | interface PhoneState {
2120 | public function pickUp(): PhoneState;
2121 | public function hangUp(): PhoneState;
2122 | public function dial(): PhoneState;
2123 | }
2124 |
2125 | // states implementation
2126 | class PhoneStateIdle implements PhoneState {
2127 | public function pickUp(): PhoneState {
2128 | return new PhoneStatePickedUp();
2129 | }
2130 | public function hangUp(): PhoneState {
2131 | throw new Exception("already idle");
2132 | }
2133 | public function dial(): PhoneState {
2134 | throw new Exception("unable to dial in idle state");
2135 | }
2136 | }
2137 |
2138 | class PhoneStatePickedUp implements PhoneState {
2139 | public function pickUp(): PhoneState {
2140 | throw new Exception("already picked up");
2141 | }
2142 | public function hangUp(): PhoneState {
2143 | return new PhoneStateIdle();
2144 | }
2145 | public function dial(): PhoneState {
2146 | return new PhoneStateCalling();
2147 | }
2148 | }
2149 |
2150 | class PhoneStateCalling implements PhoneState {
2151 | public function pickUp(): PhoneState {
2152 | throw new Exception("already picked up");
2153 | }
2154 | public function hangUp(): PhoneState {
2155 | return new PhoneStateIdle();
2156 | }
2157 | public function dial(): PhoneState {
2158 | throw new Exception("already dialing");
2159 | }
2160 | }
2161 | ```
2162 |
2163 | Then we have our Phone class that changes the state on different behavior calls
2164 |
2165 | ```php
2166 | class Phone {
2167 | private $state;
2168 |
2169 | public function __construct() {
2170 | $this->state = new PhoneStateIdle();
2171 | }
2172 | public function pickUp() {
2173 | $this->state = $this->state->pickUp();
2174 | }
2175 | public function hangUp() {
2176 | $this->state = $this->state->hangUp();
2177 | }
2178 | public function dial() {
2179 | $this->state = $this->state->dial();
2180 | }
2181 | }
2182 | ```
2183 |
2184 | And then it can be used as follows and it will call the relevant state methods:
2185 |
2186 | ```php
2187 | $phone = new Phone();
2188 |
2189 | $phone->pickUp();
2190 | $phone->dial();
2191 | ```
2192 |
2193 | 📒 Template Method
2194 | ---------------
2195 |
2196 | Real world example
2197 | > Suppose we are getting some house built. The steps for building might look like
2198 | > - Prepare the base of house
2199 | > - Build the walls
2200 | > - Add roof
2201 | > - Add other floors
2202 |
2203 | > 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.
2204 |
2205 | In plain words
2206 | > Template method defines the skeleton of how a certain algorithm could be performed, but defers the implementation of those steps to the children classes.
2207 |
2208 | Wikipedia says
2209 | > 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.
2210 |
2211 | **Programmatic Example**
2212 |
2213 | 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.
2214 |
2215 | First of all we have our base class that specifies the skeleton for the build algorithm
2216 | ```php
2217 | abstract class Builder
2218 | {
2219 |
2220 | // Template method
2221 | final public function build()
2222 | {
2223 | $this->test();
2224 | $this->lint();
2225 | $this->assemble();
2226 | $this->deploy();
2227 | }
2228 |
2229 | abstract public function test();
2230 | abstract public function lint();
2231 | abstract public function assemble();
2232 | abstract public function deploy();
2233 | }
2234 | ```
2235 |
2236 | Then we can have our implementations
2237 |
2238 | ```php
2239 | class AndroidBuilder extends Builder
2240 | {
2241 | public function test()
2242 | {
2243 | echo 'Running android tests';
2244 | }
2245 |
2246 | public function lint()
2247 | {
2248 | echo 'Linting the android code';
2249 | }
2250 |
2251 | public function assemble()
2252 | {
2253 | echo 'Assembling the android build';
2254 | }
2255 |
2256 | public function deploy()
2257 | {
2258 | echo 'Deploying android build to server';
2259 | }
2260 | }
2261 |
2262 | class IosBuilder extends Builder
2263 | {
2264 | public function test()
2265 | {
2266 | echo 'Running ios tests';
2267 | }
2268 |
2269 | public function lint()
2270 | {
2271 | echo 'Linting the ios code';
2272 | }
2273 |
2274 | public function assemble()
2275 | {
2276 | echo 'Assembling the ios build';
2277 | }
2278 |
2279 | public function deploy()
2280 | {
2281 | echo 'Deploying ios build to server';
2282 | }
2283 | }
2284 | ```
2285 | And then it can be used as
2286 |
2287 | ```php
2288 | $androidBuilder = new AndroidBuilder();
2289 | $androidBuilder->build();
2290 |
2291 | // Output:
2292 | // Running android tests
2293 | // Linting the android code
2294 | // Assembling the android build
2295 | // Deploying android build to server
2296 |
2297 | $iosBuilder = new IosBuilder();
2298 | $iosBuilder->build();
2299 |
2300 | // Output:
2301 | // Running ios tests
2302 | // Linting the ios code
2303 | // Assembling the ios build
2304 | // Deploying ios build to server
2305 | ```
2306 |
2307 | ## 🚦 Wrap Up Folks
2308 |
2309 | 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.
2310 |
2311 | ## 👬 Contribution
2312 |
2313 | - Report issues
2314 | - Open pull request with improvements
2315 | - Spread the word
2316 | - Reach out with any feedback [](https://twitter.com/kamrify)
2317 |
2318 | ## License
2319 |
2320 | [](https://creativecommons.org/licenses/by/4.0/)
2321 |
--------------------------------------------------------------------------------