├── LICENSE ├── README.md └── cover.png /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2017 Soham Kamani 2 | 3 | Based on "Design patterns for humans" Copyright 2017 Kamran Ahmed 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Design Patterns For Humans](./cover.png) 2 | 3 | *** 4 |

5 | 🎉 Ultra-simplified explanation to design patterns! 🎉 6 |

7 |

8 | 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. 9 |
10 | Based on "Design patterns for humans" 11 |

12 | 13 | *** 14 | 15 | Follow me on [twitter](https://twitter.com/sohamkamani) and check out my [blog](http://sohamkamani.com) 16 | 17 | 🚀 Introduction 18 | ================= 19 | 20 | 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. 21 | 22 | > Design patterns solutions to recurring problems guidelines on how to tackle certain problems 23 | 24 | Wikipedia describes them as 25 | 26 | > 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. 27 | 28 | ⚠️ Be Careful 29 | ----------------- 30 | - Design patterns are not a silver bullet to all your problems. 31 | - Do not try to force them bad things are supposed to happen, if done so. Keep in mind that design patterns are solutions **to** problems, not solutions **finding** problems so don't overthink. 32 | - 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. 33 | 34 | 35 | 36 | 37 | ## 🐢 Before you start 38 | 39 | - All design patterns have been implemented in [ES6](https://github.com/lukehoban/es6features), the new version of javascript. 40 | - Since javascript does not have any implementation of interfaces, the examples here use implied interfaces, which means that as long as a class has attributes and methods that a particular interface is supposed to have, it is considered to implement that interface. To make it easier to tell the interface we are using, its information can be found in the comments of every example. 41 | 42 | Types of Design Patterns 43 | ----------------- 44 | 45 | * [Creational](#creational-design-patterns) 46 | * [Structural](#structural-design-patterns) 47 | * [Behavioral](#behavioral-design-patterns) 48 | 49 | 50 | Creational Design Patterns 51 | ========================== 52 | 53 | In plain words 54 | > Creational patterns are focused towards how to instantiate an object or group of related objects. 55 | 56 | Wikipedia says 57 | > 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. 58 | 59 | * [Simple Factory](#-simple-factory) 60 | * [Factory Method](#-factory-method) 61 | * [Abstract Factory](#-abstract-factory) 62 | * [Builder](#-builder) 63 | * [Prototype](#-prototype) 64 | * [Singleton](#-singleton) 65 | 66 | 🏠 Simple Factory 67 | -------------- 68 | Real world example 69 | > Consider, you are building a house and you need doors. It would be a mess if every time you need a door, you put on your carpenter clothes and start making a door in your house. Instead you get it made from a factory. 70 | 71 | In plain words 72 | > Simple factory simply generates an instance for client without exposing any instantiation logic to the client 73 | 74 | Wikipedia says 75 | > 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". 76 | 77 | **Programmatic Example** 78 | 79 | First of all we have a door interface and the implementation 80 | ```js 81 | /* 82 | Door 83 | 84 | getWidth() 85 | getHeight() 86 | 87 | */ 88 | 89 | class WoodenDoor { 90 | constructor(width, height){ 91 | this.width = width 92 | this.height = height 93 | } 94 | 95 | getWidth(){ 96 | return this.width 97 | } 98 | 99 | getHeight(){ 100 | return this.height 101 | } 102 | } 103 | ``` 104 | Then we have our door factory that makes the door and returns it 105 | 106 | ```js 107 | const DoorFactory = { 108 | makeDoor : (width, height) => new WoodenDoor(width, height) 109 | } 110 | ``` 111 | And then it can be used as 112 | 113 | ```js 114 | const door = DoorFactory.makeDoor(100, 200) 115 | console.log('Width:', door.getWidth()) 116 | console.log('Height:', door.getHeight()) 117 | ``` 118 | 119 | **When to Use?** 120 | 121 | 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. 122 | 123 | 🏭 Factory Method 124 | -------------- 125 | 126 | Real world example 127 | > 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. 128 | 129 | In plain words 130 | > It provides a way to delegate the instantiation logic to child classes. 131 | 132 | Wikipedia says 133 | > 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. 134 | 135 | **Programmatic Example** 136 | 137 | Taking our hiring manager example above. First of all we have an interviewer interface and some implementations for it 138 | 139 | ```js 140 | /* 141 | Interviewer interface 142 | 143 | askQuestions() 144 | */ 145 | 146 | class Developer { 147 | askQuestions() { 148 | console.log('Asking about design patterns!') 149 | } 150 | } 151 | 152 | class CommunityExecutive { 153 | askQuestions() { 154 | console.log('Asking about community building') 155 | } 156 | } 157 | ``` 158 | 159 | Now let us create our `HiringManager` 160 | 161 | ```js 162 | class HiringManager { 163 | 164 | takeInterview() { 165 | const interviewer = this.makeInterviewer() 166 | interviewer.askQuestions() 167 | } 168 | } 169 | ``` 170 | Now any child can extend it and provide the required interviewer 171 | ```js 172 | class DevelopmentManager extends HiringManager { 173 | makeInterviewer() { 174 | return new Developer() 175 | } 176 | } 177 | 178 | class MarketingManager extends HiringManager { 179 | makeInterviewer() { 180 | return new CommunityExecutive() 181 | } 182 | } 183 | ``` 184 | and then it can be used as 185 | 186 | ```js 187 | const devManager = new DevelopmentManager() 188 | devManager.takeInterview() // Output: Asking about design patterns 189 | 190 | const marketingManager = new MarketingManager() 191 | marketingManager.takeInterview() // Output: Asking about community building. 192 | ``` 193 | 194 | **When to use?** 195 | 196 | 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. 197 | 198 | 🔨 Abstract Factory 199 | ---------------- 200 | 201 | Real world example 202 | > 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. 203 | 204 | In plain words 205 | > A factory of factories is a factory that groups the individual but related/dependent factories together without specifying their concrete classes. 206 | 207 | Wikipedia says 208 | > The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes 209 | 210 | **Programmatic Example** 211 | 212 | Translating the door example above. First of all we have our `Door` interface and some implementation for it 213 | 214 | ```js 215 | /* 216 | Door interface : 217 | 218 | getDescription() 219 | */ 220 | 221 | class WoodenDoor { 222 | getDescription() { 223 | console.log('I am a wooden door') 224 | } 225 | } 226 | 227 | class IronDoor { 228 | getDescription() { 229 | console.log('I am an iron door') 230 | } 231 | } 232 | ``` 233 | Then we have some fitting experts for each door type 234 | 235 | ```js 236 | /* 237 | DoorFittingExpert interface : 238 | 239 | getDescription() 240 | */ 241 | 242 | class Welder { 243 | getDescription() { 244 | console.log('I can only fit iron doors') 245 | } 246 | } 247 | 248 | class Carpenter { 249 | getDescription() { 250 | console.log('I can only fit wooden doors') 251 | } 252 | } 253 | ``` 254 | 255 | 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 256 | ```js 257 | /* 258 | DoorFactory interface : 259 | 260 | makeDoor() 261 | makeFittingExpert() 262 | */ 263 | 264 | // Wooden factory to return carpenter and wooden door 265 | class WoodenDoorFactory { 266 | makeDoor(){ 267 | return new WoodenDoor() 268 | } 269 | 270 | makeFittingExpert() { 271 | return new Carpenter() 272 | } 273 | } 274 | 275 | // Iron door factory to get iron door and the relevant fitting expert 276 | class IronDoorFactory { 277 | makeDoor(){ 278 | return new IronDoor() 279 | } 280 | 281 | makeFittingExpert() { 282 | return new Welder() 283 | } 284 | } 285 | ``` 286 | And then it can be used as 287 | ```js 288 | woodenFactory = new WoodenDoorFactory() 289 | 290 | door = woodenFactory.makeDoor() 291 | expert = woodenFactory.makeFittingExpert() 292 | 293 | door.getDescription() // Output: I am a wooden door 294 | expert.getDescription() // Output: I can only fit wooden doors 295 | 296 | // Same for Iron Factory 297 | ironFactory = new IronDoorFactory() 298 | 299 | door = ironFactory.makeDoor() 300 | expert = ironFactory.makeFittingExpert() 301 | 302 | door.getDescription() // Output: I am an iron door 303 | expert.getDescription() // Output: I can only fit iron doors 304 | ``` 305 | 306 | 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. 307 | 308 | **When to use?** 309 | 310 | When there are interrelated dependencies with not-that-simple creation logic involved 311 | 312 | 👷 Builder 313 | -------------------------------------------- 314 | Real world example 315 | > 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. 316 | 317 | In plain words 318 | > 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. 319 | 320 | Wikipedia says 321 | > The builder pattern is an object creation software design pattern with the intentions of finding a solution to the telescoping constructor anti-pattern. 322 | 323 | 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: 324 | 325 | ```js 326 | constructor(size, cheese = true, pepperoni = true, tomato = false, lettuce = true) { 327 | // ... 328 | } 329 | ``` 330 | 331 | 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. 332 | 333 | **Programmatic Example** 334 | 335 | The sane alternative is to use the builder pattern. First of all we have our burger that we want to make 336 | 337 | ```js 338 | class Burger { 339 | constructor(builder) { 340 | this.size = builder.size 341 | this.cheeze = builder.cheeze || false 342 | this.pepperoni = builder.pepperoni || false 343 | this.lettuce = builder.lettuce || false 344 | this.tomato = builder.tomato || false 345 | } 346 | } 347 | ``` 348 | 349 | And then we have the builder 350 | 351 | ```js 352 | class BurgerBuilder { 353 | 354 | constructor(size) { 355 | this.size = size 356 | } 357 | 358 | addPepperoni() { 359 | this.pepperoni = true 360 | return this 361 | } 362 | 363 | addLettuce() { 364 | this.lettuce = true 365 | return this 366 | } 367 | 368 | addCheeze() { 369 | this.cheeze = true 370 | return this 371 | } 372 | 373 | addTomato() { 374 | this.tomato = true 375 | return this 376 | } 377 | 378 | build() { 379 | return new Burger(this) 380 | } 381 | } 382 | ``` 383 | And then it can be used as: 384 | 385 | ```js 386 | const burger = (new BurgerBuilder(14)) 387 | .addPepperoni() 388 | .addLettuce() 389 | .addTomato() 390 | .build() 391 | ``` 392 | 393 | __Javascript specific tip__ : When you find that the number of arguments to a function or method are too many (normally any more than 2 arguments is considered too much), use a single object argument instead of multiple arguments. This serves two purposes : 394 | 395 | 1. It makes your code look less cluttered, since there is only one argument. 396 | 2. You don't have to worry about the order of arguments since arguments are now passed as named properties of the object. 397 | 398 | For example : 399 | 400 | ```js 401 | const burger = new Burger({ 402 | size : 14, 403 | pepperoni : true, 404 | cheeze : false, 405 | lettuce : true, 406 | tomato : true 407 | }) 408 | ``` 409 | 410 | instead of : 411 | 412 | ``` 413 | const burger = new Burger(14, true, false, true, true) 414 | ``` 415 | 416 | **When to use?** 417 | 418 | 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. 419 | 420 | [Read more...](https://www.sohamkamani.com/javascript/builder-pattern/) 421 | 422 | 🐑 Prototype 423 | ------------ 424 | Real world example 425 | > 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 426 | 427 | In plain words 428 | > Create object based on an existing object through cloning. 429 | 430 | Wikipedia says 431 | > 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. 432 | 433 | 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. 434 | 435 | **Programmatic Example** 436 | 437 | First of all we have our Sheep that we want to clone 438 | 439 | ```js 440 | class Sheep { 441 | constructor(name, category = "Mountain Sheep") { 442 | this.name = name; 443 | this.category = category; 444 | } 445 | 446 | setName(name) { 447 | this.name = name; 448 | } 449 | 450 | getName() { 451 | console.log(this.name); 452 | } 453 | 454 | setCategory(category) { 455 | this.category = category; 456 | } 457 | 458 | getCategory() { 459 | console.log(this.category); 460 | } 461 | } 462 | ``` 463 | 464 | And then we have a SheepPrototype object that clones objects given a prototype object. Its constructor function accepts a prototype of type Sheep 465 | 466 | ```js 467 | class SheepPrototype { 468 | constructor(proto) { 469 | this.proto = proto; 470 | } 471 | 472 | clone() { 473 | return new Sheep(this.proto.name, this.proto.category); 474 | } 475 | } 476 | ``` 477 | 478 | Then it can be cloned like below 479 | 480 | ```js 481 | const originalSheep = new Sheep("Jolly"); 482 | originalSheep.getName(); // Jolly 483 | originalSheep.getCategory(); // Mountain Sheep 484 | 485 | // Clone and modify what is required 486 | const prototype = new SheepPrototype(originalSheep); 487 | const clonedSheep = prototype.clone(); 488 | clonedSheep.setName("Dolly"); 489 | clonedSheep.getName(); // Dolly 490 | clonedSheep.getCategory(); // Mountain sheep 491 | ``` 492 | 493 | This was the classical implementation of the Prototype pattern, but JavaScript can do this far more effectively using its [built-in prototype facility](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes). 494 | 495 | **When to use?** 496 | 497 | When an object is required that is similar to existing object or when the creation would be expensive as compared to cloning. 498 | 499 | 💍 Singleton 500 | ------------ 501 | Real world example 502 | > 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. 503 | 504 | In plain words 505 | > Ensures that only one object of a particular class is ever created. 506 | 507 | Wikipedia says 508 | > 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. 509 | 510 | 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 it mocking the singleton could be difficult. 511 | 512 | **Programmatic Example** 513 | 514 | In javascript, singletons can be implemented using the module pattern. Private variables and functions are hidden in a function closure, and public methods are selectively exposed. 515 | ```js 516 | const president = (function(){ 517 | const presidentsPrivateInformation = 'Super private' 518 | 519 | const name = 'Turd Sandwich' 520 | 521 | const getName = () => name 522 | 523 | return { 524 | getName 525 | } 526 | }()) 527 | ``` 528 | 529 | Here, `presidentsPrivateInformation` and `name` are kept private. However, `name` can be accessed with the exposed `president.getName` method. 530 | 531 | ```js 532 | president.getName() // Outputs 'Turd Sandwich' 533 | president.name // Outputs undefined 534 | president.presidentsPrivateInformation // Outputs undefined 535 | ``` 536 | 537 | Structural Design Patterns 538 | ========================== 539 | In plain words 540 | > 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?" 541 | 542 | Wikipedia says 543 | > In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities. 544 | 545 | * [Adapter](#-adapter) 546 | * [Bridge](#-bridge) 547 | * [Composite](#-composite) 548 | * [Decorator](#-decorator) 549 | * [Facade](#-facade) 550 | * [Flyweight](#-flyweight) 551 | * [Proxy](#-proxy) 552 | 553 | 🔌 Adapter 554 | ------- 555 | Real world example 556 | > 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. 557 | > 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. 558 | > Yet another example would be a translator translating words spoken by one person to another 559 | 560 | In plain words 561 | > Adapter pattern lets you wrap an otherwise incompatible object in an adapter to make it compatible with another class. 562 | 563 | Wikipedia says 564 | > 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. 565 | 566 | **Programmatic Example** 567 | 568 | Consider a game where there is a hunter and he hunts lions. 569 | 570 | First we have an interface `Lion` that all types of lions have to implement 571 | 572 | ```js 573 | /* 574 | Lion interface : 575 | 576 | roar() 577 | */ 578 | 579 | class AfricanLion { 580 | roar() {} 581 | } 582 | 583 | class AsianLion { 584 | roar() {} 585 | } 586 | ``` 587 | And hunter expects any implementation of `Lion` interface to hunt. 588 | ```js 589 | class Hunter { 590 | hunt(lion) { 591 | // ... some code before 592 | lion.roar() 593 | //... some code after 594 | } 595 | } 596 | ``` 597 | 598 | 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 599 | 600 | ```js 601 | // This needs to be added to the game 602 | class WildDog { 603 | bark() { 604 | } 605 | } 606 | 607 | // Adapter around wild dog to make it compatible with our game 608 | class WildDogAdapter { 609 | 610 | constructor(dog) { 611 | this.dog = dog; 612 | } 613 | 614 | roar() { 615 | this.dog.bark(); 616 | } 617 | } 618 | ``` 619 | And now the `WildDog` can be used in our game using `WildDogAdapter`. 620 | 621 | ```js 622 | wildDog = new WildDog() 623 | wildDogAdapter = new WildDogAdapter(wildDog) 624 | 625 | hunter = new Hunter() 626 | hunter.hunt(wildDogAdapter) 627 | ``` 628 | 629 | 🚡 Bridge 630 | ------ 631 | Real world example 632 | > 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. 633 | 634 | ![With and without the bridge pattern](https://cloud.githubusercontent.com/assets/11269635/23065293/33b7aea0-f515-11e6-983f-98823c9845ee.png) 635 | 636 | In Plain Words 637 | > Bridge pattern is about preferring composition over inheritance. Implementation details are pushed from a hierarchy to another object with a separate hierarchy. 638 | 639 | Wikipedia says 640 | > 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" 641 | 642 | **Programmatic Example** 643 | 644 | Translating our WebPage example from above. Here we have the `WebPage` hierarchy 645 | 646 | ```js 647 | /* 648 | Webpage interface : 649 | 650 | constructor(theme) 651 | getContent() 652 | */ 653 | 654 | class About{ 655 | constructor(theme) { 656 | this.theme = theme 657 | } 658 | 659 | getContent() { 660 | return `About page in ${this.theme.getColor()}` 661 | } 662 | } 663 | 664 | class Careers{ 665 | constructor(theme) { 666 | this.theme = theme 667 | } 668 | 669 | getContent() { 670 | return `Careers page in ${this.theme.getColor()}` 671 | } 672 | } 673 | ``` 674 | And the separate theme hierarchy 675 | ```js 676 | /* 677 | Theme interface : 678 | 679 | getColor() 680 | */ 681 | 682 | class DarkTheme{ 683 | getColor() { 684 | return 'Dark Black' 685 | } 686 | } 687 | class LightTheme{ 688 | getColor() { 689 | return 'Off white' 690 | } 691 | } 692 | class AquaTheme{ 693 | getColor() { 694 | return 'Light blue' 695 | } 696 | } 697 | ``` 698 | And both the hierarchies 699 | ```js 700 | const darkTheme = new DarkTheme() 701 | 702 | const about = new About(darkTheme) 703 | const careers = new Careers(darkTheme) 704 | 705 | console.log(about.getContent() )// "About page in Dark Black" 706 | console.log(careers.getContent() )// "Careers page in Dark Black" 707 | ``` 708 | 709 | 🌿 Composite 710 | ----------------- 711 | 712 | Real world example 713 | > Every organization is composed of employees. Each of the employees has 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. 714 | 715 | In plain words 716 | > Composite pattern lets clients to treat the individual objects in a uniform manner. 717 | 718 | Wikipedia says 719 | > 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. 720 | 721 | **Programmatic Example** 722 | 723 | Taking our employees example from above. Here we have different employee types 724 | 725 | ```js 726 | /* 727 | Employee interface : 728 | 729 | constructor(name, salary) 730 | getName() 731 | setSalary() 732 | getSalary() 733 | getRoles() 734 | */ 735 | 736 | class Developer { 737 | 738 | constructor(name, salary) { 739 | this.name = name 740 | this.salary = salary 741 | } 742 | 743 | getName() { 744 | return this.name 745 | } 746 | 747 | setSalary(salary) { 748 | this.salary = salary 749 | } 750 | 751 | getSalary() { 752 | return this.salary 753 | } 754 | 755 | getRoles() { 756 | return this.roles 757 | } 758 | 759 | develop() { 760 | /* */ 761 | } 762 | } 763 | 764 | class Designer { 765 | 766 | constructor(name, salary) { 767 | this.name = name 768 | this.salary = salary 769 | } 770 | 771 | getName() { 772 | return this.name 773 | } 774 | 775 | setSalary(salary) { 776 | this.salary = salary 777 | } 778 | 779 | getSalary() { 780 | return this.salary 781 | } 782 | 783 | getRoles() { 784 | return this.roles 785 | } 786 | 787 | design() { 788 | /* */ 789 | } 790 | } 791 | ``` 792 | 793 | Then we have an organization which consists of several different types of employees 794 | 795 | ```js 796 | class Organization { 797 | constructor(){ 798 | this.employees = [] 799 | } 800 | 801 | addEmployee(employee) { 802 | this.employees.push(employee) 803 | } 804 | 805 | getNetSalaries() { 806 | let netSalary = 0 807 | 808 | this.employees.forEach(employee => { 809 | netSalary += employee.getSalary() 810 | }) 811 | 812 | return netSalary 813 | } 814 | } 815 | ``` 816 | 817 | And then it can be used as 818 | 819 | ```js 820 | // Prepare the employees 821 | const john = new Developer('John Doe', 12000) 822 | const jane = new Designer('Jane', 10000) 823 | 824 | // Add them to organization 825 | const organization = new Organization() 826 | organization.addEmployee(john) 827 | organization.addEmployee(jane) 828 | 829 | console.log("Net salaries: " , organization.getNetSalaries()) // Net Salaries: 22000 830 | ``` 831 | 832 | ☕ Decorator 833 | ------------- 834 | 835 | Real world example 836 | 837 | > 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. 838 | 839 | In plain words 840 | > Decorator pattern lets you dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class. 841 | 842 | Wikipedia says 843 | > 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. 844 | 845 | **Programmatic Example** 846 | 847 | Lets take coffee for example. First of all we have a simple coffee implementing the coffee interface 848 | 849 | ```js 850 | /* 851 | Coffee interface: 852 | getCost() 853 | getDescription() 854 | */ 855 | 856 | class SimpleCoffee{ 857 | 858 | getCost() { 859 | return 10 860 | } 861 | 862 | getDescription() { 863 | return 'Simple coffee' 864 | } 865 | } 866 | ``` 867 | We want to make the code extensible to allow options to modify it if required. Lets make some add-ons (decorators) 868 | ```js 869 | class MilkCoffee { 870 | 871 | 872 | constructor(coffee) { 873 | this.coffee = coffee 874 | } 875 | 876 | getCost() { 877 | return this.coffee.getCost() + 2 878 | } 879 | 880 | getDescription() { 881 | return `${this.coffee.getDescription()}, milk` 882 | } 883 | } 884 | 885 | class WhipCoffee { 886 | 887 | constructor(coffee) { 888 | this.coffee = coffee 889 | } 890 | 891 | getCost() { 892 | return this.coffee.getCost() + 5 893 | } 894 | 895 | getDescription() { 896 | return `${this.coffee.getDescription()}, whip` 897 | } 898 | } 899 | 900 | class VanillaCoffee { 901 | 902 | constructor(coffee) { 903 | this.coffee = coffee 904 | } 905 | 906 | getCost() { 907 | return this.coffee.getCost() + 3 908 | } 909 | 910 | getDescription() { 911 | return `${this.coffee.getDescription()}, vanilla` 912 | } 913 | } 914 | 915 | ``` 916 | 917 | Lets make a coffee now 918 | 919 | ```js 920 | let someCoffee 921 | 922 | someCoffee = new SimpleCoffee() 923 | console.log(someCoffee.getCost())// 10 924 | console.log(someCoffee.getDescription())// Simple Coffee 925 | 926 | someCoffee = new MilkCoffee(someCoffee) 927 | console.log(someCoffee.getCost())// 12 928 | console.log(someCoffee.getDescription())// Simple Coffee, milk 929 | 930 | someCoffee = new WhipCoffee(someCoffee) 931 | console.log(someCoffee.getCost())// 17 932 | console.log(someCoffee.getDescription())// Simple Coffee, milk, whip 933 | 934 | someCoffee = new VanillaCoffee(someCoffee) 935 | console.log(someCoffee.getCost())// 20 936 | console.log(someCoffee.getDescription())// Simple Coffee, milk, whip, vanilla 937 | ``` 938 | 939 | 📦 Facade 940 | ---------------- 941 | 942 | Real world example 943 | > 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. 944 | 945 | In plain words 946 | > Facade pattern provides a simplified interface to a complex subsystem. 947 | 948 | Wikipedia says 949 | > A facade is an object that provides a simplified interface to a larger body of code, such as a class library. 950 | 951 | **Programmatic Example** 952 | Taking our computer example from above. Here we have the computer class 953 | 954 | ```js 955 | class Computer { 956 | 957 | getElectricShock() { 958 | console.log('Ouch!') 959 | } 960 | 961 | makeSound() { 962 | console.log('Beep beep!') 963 | } 964 | 965 | showLoadingScreen() { 966 | console.log('Loading..') 967 | } 968 | 969 | bam() { 970 | console.log('Ready to be used!') 971 | } 972 | 973 | closeEverything() { 974 | console.log('Bup bup bup buzzzz!') 975 | } 976 | 977 | sooth() { 978 | console.log('Zzzzz') 979 | } 980 | 981 | pullCurrent() { 982 | console.log('Haaah!') 983 | } 984 | } 985 | ``` 986 | Here we have the facade 987 | ```js 988 | class ComputerFacade 989 | { 990 | constructor(computer) { 991 | this.computer = computer 992 | } 993 | 994 | turnOn() { 995 | this.computer.getElectricShock() 996 | this.computer.makeSound() 997 | this.computer.showLoadingScreen() 998 | this.computer.bam() 999 | } 1000 | 1001 | turnOff() { 1002 | this.computer.closeEverything() 1003 | this.computer.pullCurrent() 1004 | this.computer.sooth() 1005 | } 1006 | } 1007 | ``` 1008 | Now to use the facade 1009 | ```js 1010 | const computer = new ComputerFacade(new Computer()) 1011 | computer.turnOn() // Ouch! Beep beep! Loading.. Ready to be used! 1012 | computer.turnOff() // Bup bup buzzz! Haah! Zzzzz 1013 | ``` 1014 | 1015 | 🍃 Flyweight 1016 | --------- 1017 | 1018 | Real world example 1019 | > 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. 1020 | 1021 | In plain words 1022 | > It is used to minimize memory usage or computational expenses by sharing as much as possible with similar objects. 1023 | 1024 | Wikipedia says 1025 | > 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. 1026 | 1027 | **Programmatic example** 1028 | Translating our tea example from above. First of all we have tea types and tea maker 1029 | 1030 | ```js 1031 | // Anything that will be cached is flyweight. 1032 | // Types of tea here will be flyweights. 1033 | class KarakTea { 1034 | } 1035 | 1036 | // Acts as a factory and saves the tea 1037 | class TeaMaker { 1038 | constructor(){ 1039 | this.availableTea = {} 1040 | } 1041 | 1042 | make(preference) { 1043 | this.availableTea[preference] = this.availableTea[preference] || (new KarakTea()) 1044 | return this.availableTea[preference] 1045 | } 1046 | } 1047 | ``` 1048 | 1049 | Then we have the `TeaShop` which takes orders and serves them 1050 | 1051 | ```js 1052 | class TeaShop { 1053 | constructor(teaMaker) { 1054 | this.teaMaker = teaMaker 1055 | this.orders = [] 1056 | } 1057 | 1058 | takeOrder(teaType, table) { 1059 | this.orders[table] = this.teaMaker.make(teaType) 1060 | } 1061 | 1062 | serve() { 1063 | this.orders.forEach((order, index) => { 1064 | console.log(`Serving tea to table# ${index}`) 1065 | }) 1066 | } 1067 | } 1068 | ``` 1069 | And it can be used as below 1070 | 1071 | ```js 1072 | const teaMaker = new TeaMaker() 1073 | const shop = new TeaShop(teaMaker) 1074 | 1075 | shop.takeOrder('less sugar', 1) 1076 | shop.takeOrder('more milk', 2) 1077 | shop.takeOrder('without sugar', 5) 1078 | 1079 | shop.serve() 1080 | // Serving tea to table# 1 1081 | // Serving tea to table# 2 1082 | // Serving tea to table# 5 1083 | ``` 1084 | 1085 | 🎱 Proxy 1086 | ------------------- 1087 | Real world example 1088 | > 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. 1089 | 1090 | In plain words 1091 | > Using the proxy pattern, a class represents the functionality of another class. 1092 | 1093 | Wikipedia says 1094 | > 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. 1095 | 1096 | **Programmatic Example** 1097 | Taking our security door example from above. Firstly we have the door interface and an implementation of door 1098 | 1099 | ```js 1100 | /* 1101 | Door interface : 1102 | 1103 | open() 1104 | close() 1105 | */ 1106 | 1107 | class LabDoor { 1108 | open() { 1109 | console.log('Opening lab door') 1110 | } 1111 | 1112 | close() { 1113 | console.log('Closing the lab door') 1114 | } 1115 | } 1116 | ``` 1117 | Then we have a proxy to secure any doors that we want 1118 | ```js 1119 | class Security { 1120 | constructor(door) { 1121 | this.door = door 1122 | } 1123 | 1124 | open(password) { 1125 | if (this.authenticate(password)) { 1126 | this.door.open() 1127 | } else { 1128 | console.log('Big no! It ain\'t possible.') 1129 | } 1130 | } 1131 | 1132 | authenticate(password) { 1133 | return password === 'ecr@t' 1134 | } 1135 | 1136 | close() { 1137 | this.door.close() 1138 | } 1139 | } 1140 | ``` 1141 | And here is how it can be used 1142 | ```js 1143 | const door = new Security(new LabDoor()) 1144 | door.open('invalid') // Big no! It ain't possible. 1145 | 1146 | door.open('ecr@t') // Opening lab door 1147 | door.close() // Closing lab door 1148 | ``` 1149 | 1150 | Behavioral Design Patterns 1151 | ========================== 1152 | 1153 | In plain words 1154 | > 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?" 1155 | 1156 | Wikipedia says 1157 | > 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. 1158 | 1159 | * [Chain of Responsibility](#-chain-of-responsibility) 1160 | * [Command](#-command) 1161 | * [Iterator](#-iterator) 1162 | * [Mediator](#-mediator) 1163 | * [Memento](#-memento) 1164 | * [Observer](#-observer) 1165 | * [Visitor](#-visitor) 1166 | * [Strategy](#-strategy) 1167 | * [State](#-state) 1168 | * [Template Method](#-template-method) 1169 | 1170 | 🔗 Chain of Responsibility 1171 | ----------------------- 1172 | 1173 | Real world example 1174 | > 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. 1175 | 1176 | In plain words 1177 | > 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. 1178 | 1179 | Wikipedia says 1180 | > 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. 1181 | 1182 | **Programmatic Example** 1183 | 1184 | Translating our account example above. First of all we have a base account having the logic for chaining the accounts together and some accounts 1185 | 1186 | ```js 1187 | class Account { 1188 | 1189 | setNext(account) { 1190 | this.successor = account 1191 | } 1192 | 1193 | pay(amountToPay) { 1194 | if (this.canPay(amountToPay)) { 1195 | console.log(`Paid ${amountToPay} using ${this.name}`) 1196 | } else if (this.successor) { 1197 | console.log(`Cannot pay using ${this.name}. Proceeding...`) 1198 | this.successor.pay(amountToPay) 1199 | } else { 1200 | console.log('None of the accounts have enough balance') 1201 | } 1202 | } 1203 | 1204 | canPay(amount) { 1205 | return this.balance >= amount 1206 | } 1207 | } 1208 | 1209 | class Bank extends Account { 1210 | constructor(balance) { 1211 | super() 1212 | this.name = 'bank' 1213 | this.balance = balance 1214 | } 1215 | } 1216 | 1217 | class Paypal extends Account { 1218 | constructor(balance) { 1219 | super() 1220 | this.name = 'Paypal' 1221 | this.balance = balance 1222 | } 1223 | } 1224 | 1225 | class Bitcoin extends Account { 1226 | constructor(balance) { 1227 | super() 1228 | this.name = 'bitcoin' 1229 | this.balance = balance 1230 | } 1231 | } 1232 | ``` 1233 | 1234 | Now let's prepare the chain using the links defined above (i.e. Bank, Paypal, Bitcoin) 1235 | 1236 | ```js 1237 | // Let's prepare a chain like below 1238 | // bank.paypal.bitcoin 1239 | // 1240 | // First priority bank 1241 | // If bank can't pay then paypal 1242 | // If paypal can't pay then bit coin 1243 | 1244 | const bank = new Bank(100) // Bank with balance 100 1245 | const paypal = new Paypal(200) // Paypal with balance 200 1246 | const bitcoin = new Bitcoin(300) // Bitcoin with balance 300 1247 | 1248 | bank.setNext(paypal) 1249 | paypal.setNext(bitcoin) 1250 | 1251 | // Let's try to pay using the first priority i.e. bank 1252 | bank.pay(259) 1253 | 1254 | // Output will be 1255 | // ============== 1256 | // Cannot pay using bank. Proceeding .. 1257 | // Cannot pay using paypal. Proceeding ..: 1258 | // Paid 259 using Bitcoin! 1259 | ``` 1260 | 1261 | 👮 Command 1262 | ------- 1263 | 1264 | Real world example 1265 | > A generic example would be you ordering a food at 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. 1266 | > Another example would be you (i.e. `Client`) switching on (i.e. `Command`) the television (i.e. `Receiver`) using a remote control (`Invoker`). 1267 | 1268 | In plain words 1269 | > Allows you to encapsulate actions in objects. The key idea behind this pattern is to provide the means to decouple client from receiver. 1270 | 1271 | Wikipedia says 1272 | > 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. 1273 | 1274 | **Programmatic Example** 1275 | 1276 | First of all we have the receiver that has the implementation of every action that could be performed 1277 | ```js 1278 | // Receiver 1279 | class Bulb { 1280 | turnOn() { 1281 | console.log('Bulb has been lit') 1282 | } 1283 | 1284 | turnOff() { 1285 | console.log('Darkness!') 1286 | } 1287 | } 1288 | ``` 1289 | then we have an interface that each of the commands are going to implement and then we have a set of commands 1290 | ```js 1291 | /* 1292 | Command interface : 1293 | 1294 | execute() 1295 | undo() 1296 | redo() 1297 | */ 1298 | 1299 | // Command 1300 | class TurnOnCommand { 1301 | constructor(bulb) { 1302 | this.bulb = bulb 1303 | } 1304 | 1305 | execute() { 1306 | this.bulb.turnOn() 1307 | } 1308 | 1309 | undo() { 1310 | this.bulb.turnOff() 1311 | } 1312 | 1313 | redo() { 1314 | this.execute() 1315 | } 1316 | } 1317 | 1318 | class TurnOffCommand { 1319 | constructor(bulb) { 1320 | this.bulb = bulb 1321 | } 1322 | 1323 | execute() { 1324 | this.bulb.turnOff() 1325 | } 1326 | 1327 | undo() { 1328 | this.bulb.turnOn() 1329 | } 1330 | 1331 | redo() { 1332 | this.execute() 1333 | } 1334 | } 1335 | ``` 1336 | Then we have an `Invoker` with whom the client will interact to process any commands 1337 | ```js 1338 | // Invoker 1339 | class RemoteControl { 1340 | submit(command) { 1341 | command.execute() 1342 | } 1343 | } 1344 | ``` 1345 | Finally let's see how we can use it in our client 1346 | ```js 1347 | const bulb = new Bulb() 1348 | 1349 | const turnOn = new TurnOnCommand(bulb) 1350 | const turnOff = new TurnOffCommand(bulb) 1351 | 1352 | const remote = new RemoteControl() 1353 | remote.submit(turnOn) // Bulb has been lit! 1354 | remote.submit(turnOff) // Darkness! 1355 | ``` 1356 | 1357 | 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. 1358 | 1359 | ➿ Iterator 1360 | -------- 1361 | 1362 | Real world example 1363 | > 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. 1364 | 1365 | In plain words 1366 | > It presents a way to access the elements of an object without exposing the underlying presentation. 1367 | 1368 | Wikipedia says 1369 | > 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. 1370 | 1371 | **Programmatic example** 1372 | Translating our radio stations example from above. First of all we have `RadioStation` 1373 | 1374 | ```js 1375 | class RadioStation { 1376 | constructor(frequency) { 1377 | this.frequency = frequency 1378 | } 1379 | 1380 | getFrequency() { 1381 | return this.frequency 1382 | } 1383 | } 1384 | ``` 1385 | Then we have our iterator 1386 | 1387 | ```js 1388 | class StationList { 1389 | constructor(){ 1390 | this.stations = [] 1391 | } 1392 | 1393 | addStation(station) { 1394 | this.stations.push(station) 1395 | } 1396 | 1397 | removeStation(toRemove) { 1398 | const toRemoveFrequency = toRemove.getFrequency() 1399 | this.stations = this.stations.filter(station => { 1400 | return station.getFrequency() !== toRemoveFrequency 1401 | }) 1402 | } 1403 | } 1404 | ``` 1405 | And then it can be used as 1406 | ```js 1407 | const stationList = new StationList() 1408 | 1409 | stationList.addStation(new RadioStation(89)) 1410 | stationList.addStation(new RadioStation(101)) 1411 | stationList.addStation(new RadioStation(102)) 1412 | stationList.addStation(new RadioStation(103.2)) 1413 | 1414 | stationList.stations.forEach(station => console.log(station.getFrequency())) 1415 | 1416 | stationList.removeStation(new RadioStation(89)) // Will remove station 89 1417 | ``` 1418 | 1419 | 👽 Mediator 1420 | ======== 1421 | 1422 | Real world example 1423 | > 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. 1424 | 1425 | In plain words 1426 | > 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. 1427 | 1428 | Wikipedia says 1429 | > 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. 1430 | 1431 | **Programmatic Example** 1432 | 1433 | Here is the simplest example of a chat room (i.e. mediator) with users (i.e. colleagues) sending messages to each other. 1434 | 1435 | First of all, we have the mediator i.e. the chat room 1436 | 1437 | ```js 1438 | // Mediator 1439 | class ChatRoom { 1440 | showMessage(user, message) { 1441 | const time = new Date() 1442 | const sender = user.getName() 1443 | 1444 | console.log(`${time}[${sender}]: ${message}`) 1445 | } 1446 | } 1447 | ``` 1448 | 1449 | Then we have our users i.e. colleagues 1450 | ```js 1451 | class User { 1452 | constructor(name, chatMediator) { 1453 | this.name = name 1454 | this.chatMediator = chatMediator 1455 | } 1456 | 1457 | getName() { 1458 | return this.name 1459 | } 1460 | 1461 | send(message) { 1462 | this.chatMediator.showMessage(this, message) 1463 | } 1464 | } 1465 | ``` 1466 | And the usage 1467 | ```js 1468 | const mediator = new ChatRoom() 1469 | 1470 | const john = new User('John Doe', mediator) 1471 | const jane = new User('Jane Doe', mediator) 1472 | 1473 | john.send('Hi there!') 1474 | jane.send('Hey!') 1475 | 1476 | // Output will be 1477 | // Feb 14, 10:58 [John]: Hi there! 1478 | // Feb 14, 10:58 [Jane]: Hey! 1479 | ``` 1480 | 1481 | 💾 Memento 1482 | ------- 1483 | Real world example 1484 | > 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). 1485 | 1486 | In plain words 1487 | > 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. 1488 | 1489 | Wikipedia says 1490 | > The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback). 1491 | 1492 | Usually useful when you need to provide some sort of undo functionality. 1493 | 1494 | **Programmatic Example** 1495 | 1496 | Lets take an example of text editor which keeps saving the state from time to time and that you can restore if you want. 1497 | 1498 | First of all we have our memento object that will be able to hold the editor state 1499 | 1500 | ```js 1501 | class EditorMemento { 1502 | constructor(content) { 1503 | this._content = content 1504 | } 1505 | 1506 | getContent() { 1507 | return this._content 1508 | } 1509 | } 1510 | ``` 1511 | 1512 | Then we have our editor i.e. originator that is going to use memento object 1513 | 1514 | ```js 1515 | class Editor { 1516 | constructor(){ 1517 | this._content = '' 1518 | } 1519 | 1520 | type(words) { 1521 | this._content += ` ${words}` 1522 | } 1523 | 1524 | getContent() { 1525 | return this._content 1526 | } 1527 | 1528 | save() { 1529 | return new EditorMemento(this._content) 1530 | } 1531 | 1532 | restore(memento) { 1533 | this._content = memento.getContent() 1534 | } 1535 | } 1536 | ``` 1537 | 1538 | And then it can be used as 1539 | 1540 | ```js 1541 | const editor = new Editor() 1542 | 1543 | // Type some stuff 1544 | editor.type('This is the first sentence.') 1545 | editor.type('This is second.') 1546 | 1547 | // Save the state to restore to : This is the first sentence. This is second. 1548 | const saved = editor.save() 1549 | 1550 | // Type some more 1551 | editor.type('And this is third.') 1552 | 1553 | // Output: Content before Saving 1554 | console.log(editor.getContent())// This is the first sentence. This is second. And this is third. 1555 | 1556 | // Restoring to last saved state 1557 | editor.restore(saved) 1558 | 1559 | console.log(editor.getContent()) // This is the first sentence. This is second. 1560 | ``` 1561 | 1562 | 😎 Observer 1563 | -------- 1564 | 1565 | (Otherwise known as _"pub-sub"_) 1566 | 1567 | Real world example 1568 | > 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. 1569 | 1570 | In plain words 1571 | > Defines a dependency between objects so that whenever an object changes its state, all its dependents are notified. 1572 | 1573 | Wikipedia says 1574 | > 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. 1575 | 1576 | **Programmatic example** 1577 | 1578 | Translating our example from above. First of all we have job seekers that need to be notified for a job posting 1579 | ```js 1580 | const JobPost = title => ({ 1581 | title: title 1582 | }) 1583 | 1584 | class JobSeeker { 1585 | constructor(name) { 1586 | this._name = name 1587 | } 1588 | 1589 | notify(jobPost) { 1590 | console.log(this._name, 'has been notified of a new posting :', jobPost.title) 1591 | } 1592 | } 1593 | ``` 1594 | Then we have our job postings to which the job seekers will subscribe 1595 | ```js 1596 | class JobBoard { 1597 | constructor() { 1598 | this._subscribers = [] 1599 | } 1600 | 1601 | subscribe(jobSeeker) { 1602 | this._subscribers.push(jobSeeker) 1603 | } 1604 | 1605 | addJob(jobPosting) { 1606 | this._subscribers.forEach(subscriber => { 1607 | subscriber.notify(jobPosting) 1608 | }) 1609 | } 1610 | } 1611 | ``` 1612 | Then it can be used as 1613 | ```js 1614 | // Create subscribers 1615 | const jonDoe = new JobSeeker('John Doe') 1616 | const janeDoe = new JobSeeker('Jane Doe') 1617 | const kaneDoe = new JobSeeker('Kane Doe') 1618 | 1619 | // Create publisher and attach subscribers 1620 | const jobBoard = new JobBoard() 1621 | jobBoard.subscribe(jonDoe) 1622 | jobBoard.subscribe(janeDoe) 1623 | 1624 | // Add a new job and see if subscribers get notified 1625 | jobBoard.addJob(JobPost('Software Engineer')) 1626 | 1627 | // Output 1628 | // John Doe has been notified of a new posting : Software Engineer 1629 | // Jane Doe has been notified of a new posting : Software Engineer 1630 | ``` 1631 | 1632 | 🏃 Visitor 1633 | ------- 1634 | Real world example 1635 | > 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 let's 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. 1636 | 1637 | In plain words 1638 | > Visitor pattern let's you add further operations to objects without having to modify them. 1639 | 1640 | Wikipedia says 1641 | > 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. 1642 | 1643 | **Programmatic example** 1644 | 1645 | 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 1646 | 1647 | We have our implementations for the animals 1648 | ```js 1649 | class Monkey { 1650 | shout() { 1651 | console.log('Ooh oo aa aa!') 1652 | } 1653 | 1654 | accept(operation) { 1655 | operation.visitMonkey(this) 1656 | } 1657 | } 1658 | 1659 | class Lion { 1660 | roar() { 1661 | console.log('Roaaar!') 1662 | } 1663 | 1664 | accept(operation) { 1665 | operation.visitLion(this) 1666 | } 1667 | } 1668 | 1669 | class Dolphin { 1670 | speak() { 1671 | console.log('Tuut tuttu tuutt!') 1672 | } 1673 | 1674 | accept(operation) { 1675 | operation.visitDolphin(this) 1676 | } 1677 | } 1678 | ``` 1679 | Let's implement our visitor 1680 | ```js 1681 | const speak = { 1682 | visitMonkey(monkey){ 1683 | monkey.shout() 1684 | }, 1685 | visitLion(lion){ 1686 | lion.roar() 1687 | }, 1688 | visitDolphin(dolphin){ 1689 | dolphin.speak() 1690 | } 1691 | } 1692 | ``` 1693 | 1694 | And then it can be used as 1695 | ```js 1696 | const monkey = new Monkey() 1697 | const lion = new Lion() 1698 | const dolphin = new Dolphin() 1699 | 1700 | monkey.accept(speak) // Ooh oo aa aa! 1701 | lion.accept(speak) // Roaaar! 1702 | dolphin.accept(speak) // Tuut tutt tuutt! 1703 | ``` 1704 | We could have done this simply by having a 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. 1705 | 1706 | ```js 1707 | const jump = { 1708 | visitMonkey(monkey) { 1709 | console.log('Jumped 20 feet high! on to the tree!') 1710 | }, 1711 | visitLion(lion) { 1712 | console.log('Jumped 7 feet! Back on the ground!') 1713 | }, 1714 | visitDolphin(dolphin) { 1715 | console.log('Walked on water a little and disappeared') 1716 | } 1717 | } 1718 | ``` 1719 | And for the usage 1720 | ```js 1721 | monkey.accept(speak) // Ooh oo aa aa! 1722 | monkey.accept(jump) // Jumped 20 feet high! on to the tree! 1723 | 1724 | lion.accept(speak) // Roaaar! 1725 | lion.accept(jump) // Jumped 7 feet! Back on the ground! 1726 | 1727 | dolphin.accept(speak) // Tuut tutt tuutt! 1728 | dolphin.accept(jump) // Walked on water a little and disappeared 1729 | ``` 1730 | 1731 | 💡 Strategy 1732 | -------- 1733 | 1734 | Real world example 1735 | > 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. 1736 | 1737 | In plain words 1738 | > Strategy pattern allows you to switch the algorithm or strategy based upon the situation. 1739 | 1740 | Wikipedia says 1741 | > 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. 1742 | 1743 | **Programmatic example** 1744 | 1745 | Translating our example from above, we can easily implement this strategy in javascript using its feature of first class functions. 1746 | 1747 | ```js 1748 | const bubbleSort = dataset => { 1749 | console.log('Sorting with bubble sort') 1750 | // ... 1751 | // ... 1752 | return dataset 1753 | } 1754 | 1755 | const quickSort = dataset => { 1756 | console.log('Sorting with quick sort') 1757 | // ... 1758 | // ... 1759 | return dataset 1760 | } 1761 | ``` 1762 | 1763 | And then we have our client that is going to use any strategy 1764 | ```js 1765 | const sorter = dataset => { 1766 | if(dataset.length > 5){ 1767 | return quickSort 1768 | } else { 1769 | return bubbleSort 1770 | } 1771 | } 1772 | ``` 1773 | And it can be used as 1774 | ```js 1775 | const longDataSet = [1, 5, 4, 3, 2, 8] 1776 | const shortDataSet = [1, 5, 4] 1777 | 1778 | const sorter1 = sorter(longDataSet) 1779 | const sorter2 = sorter(shortDataSet) 1780 | 1781 | sorter1(longDataSet) // Output : Sorting with quick sort 1782 | sorter2(shortDataSet) // Output : Sorting with bubble sort 1783 | ``` 1784 | 1785 | 💢 State 1786 | ----- 1787 | Real world example 1788 | > Imagine you are using some drawing application, you choose the paint brush to draw. Now the brush changes it's 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. 1789 | 1790 | In plain words 1791 | > It lets you change the behavior of a class when the state changes. 1792 | 1793 | Wikipedia says 1794 | > 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. 1795 | > 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 1796 | 1797 | **Programmatic example** 1798 | 1799 | Let's take an example of text editor, it let's 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. 1800 | 1801 | First of all we have our transformation functions 1802 | 1803 | ```js 1804 | const upperCase = inputString => inputString.toUpperCase() 1805 | const lowerCase = inputString => inputString.toLowerCase() 1806 | const defaultTransform = inputString => inputString 1807 | ``` 1808 | Then we have our editor 1809 | ```js 1810 | class TextEditor { 1811 | constructor(transform) { 1812 | this._transform = transform 1813 | } 1814 | 1815 | setTransform(transform) { 1816 | this._transform = transform 1817 | } 1818 | 1819 | type(words) { 1820 | console.log(this._transform(words)) 1821 | } 1822 | } 1823 | ``` 1824 | And then it can be used as 1825 | ```js 1826 | const editor = new TextEditor(defaultTransform) 1827 | 1828 | editor.type('First line') 1829 | 1830 | editor.setTransform(upperCase) 1831 | 1832 | editor.type('Second line') 1833 | editor.type('Third line') 1834 | 1835 | editor.setTransform(lowerCase) 1836 | 1837 | editor.type('Fourth line') 1838 | editor.type('Fifth line') 1839 | 1840 | // Output: 1841 | // First line 1842 | // SECOND LINE 1843 | // THIRD LINE 1844 | // fourth line 1845 | // fifth line 1846 | ``` 1847 | 1848 | 📒 Template Method 1849 | --------------- 1850 | 1851 | Real world example 1852 | > Suppose we are getting some house built. The steps for building might look like 1853 | > - Prepare the base of house 1854 | > - Build the walls 1855 | > - Add roof 1856 | > - Add other floors 1857 | > 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. 1858 | 1859 | In plain words 1860 | > Template method defines the skeleton of how certain algorithm could be performed but defers the implementation of those steps to the children classes. 1861 | 1862 | Wikipedia says 1863 | > 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. 1864 | 1865 | **Programmatic Example** 1866 | 1867 | 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. 1868 | 1869 | First of all we have our base class that specifies the skeleton for the build algorithm 1870 | ```js 1871 | class Builder { 1872 | // Template method 1873 | build() { 1874 | this.test() 1875 | this.lint() 1876 | this.assemble() 1877 | this.deploy() 1878 | } 1879 | } 1880 | ``` 1881 | 1882 | Then we can have our implementations 1883 | 1884 | ```js 1885 | class AndroidBuilder extends Builder { 1886 | test() { 1887 | console.log('Running android tests') 1888 | } 1889 | 1890 | lint() { 1891 | console.log('Linting the android code') 1892 | } 1893 | 1894 | assemble() { 1895 | console.log('Assembling the android build') 1896 | } 1897 | 1898 | deploy() { 1899 | console.log('Deploying android build to server') 1900 | } 1901 | } 1902 | 1903 | class IosBuilder extends Builder { 1904 | test() { 1905 | console.log('Running ios tests') 1906 | } 1907 | 1908 | lint() { 1909 | console.log('Linting the ios code') 1910 | } 1911 | 1912 | assemble() { 1913 | console.log('Assembling the ios build') 1914 | } 1915 | 1916 | deploy() { 1917 | console.log('Deploying ios build to server') 1918 | } 1919 | } 1920 | ``` 1921 | And then it can be used as 1922 | 1923 | ```js 1924 | const androidBuilder = new AndroidBuilder() 1925 | androidBuilder.build() 1926 | 1927 | // Output: 1928 | // Running android tests 1929 | // Linting the android code 1930 | // Assembling the android build 1931 | // Deploying android build to server 1932 | 1933 | const iosBuilder = new IosBuilder() 1934 | iosBuilder.build() 1935 | 1936 | // Output: 1937 | // Running ios tests 1938 | // Linting the ios code 1939 | // Assembling the ios build 1940 | // Deploying ios build to server 1941 | ``` 1942 | 1943 | ## 🚦 Wrap Up Folks 1944 | 1945 | 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. 1946 | 1947 | ## 👬 Contribution 1948 | 1949 | - Report issues 1950 | - Open pull request with improvements 1951 | - Spread the word 1952 | 1953 | ## License 1954 | MIT © [Soham Kamani](http://sohamkamani.com) 1955 | Based on ["Design patterns for humans"](https://github.com/kamranahmedse/design-patterns-for-humans) Copyright 2017 Kamran Ahmed 1956 | -------------------------------------------------------------------------------- /cover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamkamani/javascript-design-patterns-for-humans/27f4f0527ebfc7302fe7b535713289a92a6bdc9f/cover.png --------------------------------------------------------------------------------