{"id":13392862,"url":"https://github.com/sohamkamani/javascript-design-patterns-for-humans","last_synced_at":"2026-01-24T06:50:07.175Z","repository":{"id":37701736,"uuid":"82653426","full_name":"sohamkamani/javascript-design-patterns-for-humans","owner":"sohamkamani","description":"An ultra-simplified explanation of design patterns implemented in javascript","archived":false,"fork":false,"pushed_at":"2024-01-08T05:07:39.000Z","size":98,"stargazers_count":4366,"open_issues_count":5,"forks_count":492,"subscribers_count":103,"default_branch":"master","last_synced_at":"2024-10-26T18:28:53.035Z","etag":null,"topics":["bridge-pattern","design-patterns","factory-pattern","javascript"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sohamkamani.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2017-02-21T08:10:03.000Z","updated_at":"2024-10-22T23:36:30.000Z","dependencies_parsed_at":"2024-01-11T14:12:39.933Z","dependency_job_id":"0d79ed70-6c39-4da6-895c-6fde1036c2f6","html_url":"https://github.com/sohamkamani/javascript-design-patterns-for-humans","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sohamkamani%2Fjavascript-design-patterns-for-humans","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sohamkamani%2Fjavascript-design-patterns-for-humans/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sohamkamani%2Fjavascript-design-patterns-for-humans/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sohamkamani%2Fjavascript-design-patterns-for-humans/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sohamkamani","download_url":"https://codeload.github.com/sohamkamani/javascript-design-patterns-for-humans/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243469122,"owners_count":20295691,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bridge-pattern","design-patterns","factory-pattern","javascript"],"created_at":"2024-07-30T17:00:38.309Z","updated_at":"2026-01-24T06:50:07.135Z","avatar_url":"https://github.com/sohamkamani.png","language":null,"readme":"![Design Patterns For Humans](./cover.png)\n\n***\n\u003cp align=\"center\"\u003e\n🎉 Ultra-simplified explanation to design patterns! 🎉\n\u003c/p\u003e\n\u003cp align=\"center\"\u003e\nA 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 \u003ci\u003esimplest\u003c/i\u003e way possible. \n\u003cbr/\u003e\nBased on \u003ca href=\"https://github.com/kamranahmedse/design-patterns-for-humans\"\u003e\"Design patterns for humans\"\u003c/a\u003e\n\u003c/p\u003e\n\n***\n\nFollow me on [twitter](https://twitter.com/sohamkamani) and check out my [blog](http://sohamkamani.com)\n\n🚀 Introduction\n=================\n\nDesign 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. \n\n\u003e Design patterns solutions to recurring problems guidelines on how to tackle certain problems\n\nWikipedia describes them as\n\n\u003e 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.\n\n⚠️ Be Careful\n-----------------\n- Design patterns are not a silver bullet to all your problems.\n- 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.\n- 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.\n\n\n\n\n## 🐢 Before you start\n\n- All design patterns have been implemented in [ES6](https://github.com/lukehoban/es6features), the new version of javascript.\n- 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.\n\nTypes of Design Patterns\n-----------------\n\n* [Creational](#creational-design-patterns)\n* [Structural](#structural-design-patterns)\n* [Behavioral](#behavioral-design-patterns)\n\n\nCreational Design Patterns\n==========================\n\nIn plain words\n\u003e Creational patterns are focused towards how to instantiate an object or group of related objects.\n\nWikipedia says\n\u003e 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.\n \n * [Simple Factory](#-simple-factory)\n * [Factory Method](#-factory-method)\n * [Abstract Factory](#-abstract-factory)\n * [Builder](#-builder)\n * [Prototype](#-prototype)\n * [Singleton](#-singleton)\n \n🏠 Simple Factory\n--------------\nReal world example\n\u003e 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.\n\nIn plain words\n\u003e Simple factory simply generates an instance for client without exposing any instantiation logic to the client\n\nWikipedia says\n\u003e 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\".\n\n**Programmatic Example**\n\nFirst of all we have a door interface and the implementation\n```js\n/*\nDoor\n\ngetWidth()\ngetHeight()\n\n*/\n\nclass WoodenDoor {\n  constructor(width, height){\n    this.width = width\n    this.height = height\n  }\n\n  getWidth(){\n    return this.width\n  }\n\n  getHeight(){\n    return this.height\n  }\n}\n```\nThen we have our door factory that makes the door and returns it\n\n```js\nconst DoorFactory = {\n  makeDoor : (width, height) =\u003e new WoodenDoor(width, height)\n}\n```\nAnd then it can be used as\n\n```js\nconst door = DoorFactory.makeDoor(100, 200)\nconsole.log('Width:', door.getWidth())\nconsole.log('Height:', door.getHeight())\n```\n\n**When to Use?**\n\nWhen 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. \n\n🏭 Factory Method\n--------------\n\nReal world example\n\u003e 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. \n\nIn plain words\n\u003e It provides a way to delegate the instantiation logic to child classes. \n\nWikipedia says\n\u003e 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.\n \n **Programmatic Example**\n \nTaking our hiring manager example above. First of all we have an interviewer interface and some implementations for it\n\n```js\n/*\nInterviewer interface\n\naskQuestions()\n*/\n\nclass Developer {\n  askQuestions() {\n    console.log('Asking about design patterns!')\n  }\n}\n\nclass CommunityExecutive {\n  askQuestions() {\n    console.log('Asking about community building')\n  }\n}\n```\n\nNow let us create our `HiringManager`\n\n```js\nclass HiringManager {\n        \n    takeInterview() {\n        const interviewer = this.makeInterviewer()\n        interviewer.askQuestions()\n    }\n}\n```\nNow any child can extend it and provide the required interviewer\n```js\nclass DevelopmentManager extends HiringManager {\n    makeInterviewer() {\n        return new Developer()\n    }\n}\n\nclass MarketingManager extends HiringManager {\n    makeInterviewer() {\n        return new CommunityExecutive()\n    }\n}\n```\nand then it can be used as\n\n```js\nconst devManager = new DevelopmentManager()\ndevManager.takeInterview() // Output: Asking about design patterns\n\nconst marketingManager = new MarketingManager()\nmarketingManager.takeInterview() // Output: Asking about community building.\n```\n\n**When to use?**\n\nUseful 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.\n\n🔨 Abstract Factory\n----------------\n\nReal world example\n\u003e 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.\n\nIn plain words\n\u003e A factory of factories is a factory that groups the individual but related/dependent factories together without specifying their concrete classes. \n  \nWikipedia says\n\u003e The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes\n\n**Programmatic Example**\n\nTranslating the door example above. First of all we have our `Door` interface and some implementation for it\n\n```js\n/*\nDoor interface :\n\ngetDescription()\n*/\n\nclass WoodenDoor {\n    getDescription() {\n        console.log('I am a wooden door')\n    }\n}\n\nclass IronDoor {\n    getDescription() {\n        console.log('I am an iron door')\n    }\n}\n```\nThen we have some fitting experts for each door type\n\n```js\n/*\nDoorFittingExpert interface :\n\ngetDescription()\n*/\n\nclass Welder {\n    getDescription() {\n        console.log('I can only fit iron doors')\n    }\n}\n\nclass Carpenter {\n    getDescription() {\n        console.log('I can only fit wooden doors')\n    }\n}\n```\n\nNow 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\n```js\n/*\nDoorFactory interface :\n\nmakeDoor()\nmakeFittingExpert()\n*/\n\n// Wooden factory to return carpenter and wooden door\nclass WoodenDoorFactory {\n    makeDoor(){\n        return new WoodenDoor()\n    }\n\n    makeFittingExpert() {\n        return new Carpenter()\n    }\n}\n\n// Iron door factory to get iron door and the relevant fitting expert\nclass IronDoorFactory {\n    makeDoor(){\n        return new IronDoor()\n    }\n\n    makeFittingExpert() {\n        return new Welder()\n    }\n}\n```\nAnd then it can be used as\n```js\nwoodenFactory = new WoodenDoorFactory()\n\ndoor = woodenFactory.makeDoor()\nexpert = woodenFactory.makeFittingExpert()\n\ndoor.getDescription()  // Output: I am a wooden door\nexpert.getDescription() // Output: I can only fit wooden doors\n\n// Same for Iron Factory\nironFactory = new IronDoorFactory()\n\ndoor = ironFactory.makeDoor()\nexpert = ironFactory.makeFittingExpert()\n\ndoor.getDescription()  // Output: I am an iron door\nexpert.getDescription() // Output: I can only fit iron doors\n```\n\nAs 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.   \n\n**When to use?**\n\nWhen there are interrelated dependencies with not-that-simple creation logic involved\n\n👷 Builder\n--------------------------------------------\nReal world example\n\u003e 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.\n\nIn plain words\n\u003e 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.\n \nWikipedia says\n\u003e The builder pattern is an object creation software design pattern with the intentions of finding a solution to the telescoping constructor anti-pattern.\n\nHaving 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:\n \n```js\nconstructor(size, cheese = true, pepperoni = true, tomato = false, lettuce = true) {\n    // ... \n}\n```\n\nAs 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.\n\n**Programmatic Example**\n\nThe sane alternative is to use the builder pattern. First of all we have our burger that we want to make\n\n```js\nclass Burger {\n    constructor(builder) {\n        this.size = builder.size\n        this.cheeze = builder.cheeze || false\n        this.pepperoni = builder.pepperoni || false\n        this.lettuce = builder.lettuce || false\n        this.tomato = builder.tomato || false\n    }\n}\n```\n\nAnd then we have the builder\n\n```js\nclass BurgerBuilder {\n\n    constructor(size) {\n        this.size = size\n    }\n\n    addPepperoni() {\n        this.pepperoni = true\n        return this\n    }\n\n    addLettuce() {\n        this.lettuce = true\n        return this\n    }\n\n    addCheeze() {\n        this.cheeze = true\n        return this\n    }\n\n    addTomato() {\n        this.tomato = true\n        return this\n    }\n\n    build() {\n        return new Burger(this)\n    }\n}\n```\nAnd then it can be used as:\n\n```js\nconst burger = (new BurgerBuilder(14))\n    .addPepperoni()\n    .addLettuce()\n    .addTomato()\n    .build()\n```\n\n__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 :\n\n1. It makes your code look less cluttered, since there is only one argument.\n2. You don't have to worry about the order of arguments since arguments are now passed as named properties of the object.\n\nFor example : \n\n```js\nconst burger = new Burger({\n    size : 14,\n    pepperoni : true,\n    cheeze : false,\n    lettuce : true,\n    tomato : true\n})\n```\n\ninstead of :\n\n```\nconst burger = new Burger(14, true, false, true, true)\n```\n\n**When to use?**\n\nWhen 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.\n\n[Read more...](https://www.sohamkamani.com/javascript/builder-pattern/)\n\n🐑 Prototype\n------------\nReal world example\n\u003e 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\n\nIn plain words\n\u003e Create object based on an existing object through cloning.\n\nWikipedia says\n\u003e 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.\n\nIn 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.\n\n**Programmatic Example**\n\nFirst of all we have our Sheep that we want to clone\n\n```js\nclass Sheep {\n    constructor(name, category = \"Mountain Sheep\") {\n        this.name = name;\n        this.category = category;\n    }\n\n    setName(name) {\n        this.name = name;\n    }\n\n    getName() {\n        console.log(this.name);\n    }\n\n    setCategory(category) {\n        this.category = category;\n    }\n\n    getCategory() {\n        console.log(this.category);\n    }\n}\n```\n\nAnd then we have a SheepPrototype object that clones objects given a prototype object. Its constructor function accepts a prototype of type Sheep\n\n```js\nclass SheepPrototype {\n    constructor(proto) {\n        this.proto = proto;\n    }\n\n    clone() {\n        return new Sheep(this.proto.name, this.proto.category);\n    }\n}\n```\n\nThen it can be cloned like below\n\n```js\nconst originalSheep = new Sheep(\"Jolly\");\noriginalSheep.getName(); // Jolly\noriginalSheep.getCategory(); // Mountain Sheep\n\n// Clone and modify what is required\nconst prototype = new SheepPrototype(originalSheep);\nconst clonedSheep = prototype.clone();\nclonedSheep.setName(\"Dolly\");\nclonedSheep.getName(); // Dolly\nclonedSheep.getCategory(); // Mountain sheep\n```\n\nThis 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).\n\n**When to use?**\n\nWhen an object is required that is similar to existing object or when the creation would be expensive as compared to cloning.\n\n💍 Singleton\n------------\nReal world example\n\u003e 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.\n\nIn plain words\n\u003e Ensures that only one object of a particular class is ever created.\n\nWikipedia says\n\u003e 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.\n\nSingleton 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.\n\n**Programmatic Example**\n\nIn 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.\n```js\nconst president = (function(){\n    const presidentsPrivateInformation = 'Super private'\n\n    const name = 'Turd Sandwich'\n\n    const getName = () =\u003e name\n\n    return {\n        getName\n    }\n}())\n```\n\nHere, `presidentsPrivateInformation` and `name` are kept private. However, `name` can be accessed with the exposed `president.getName` method.\n\n```js\npresident.getName() // Outputs 'Turd Sandwich'\npresident.name // Outputs undefined\npresident.presidentsPrivateInformation // Outputs undefined\n```\n\nStructural Design Patterns\n==========================\nIn plain words\n\u003e 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?\"\n\nWikipedia says\n\u003e In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.\n  \n * [Adapter](#-adapter)\n * [Bridge](#-bridge)\n * [Composite](#-composite)\n * [Decorator](#-decorator)\n * [Facade](#-facade)\n * [Flyweight](#-flyweight)\n * [Proxy](#-proxy)\n\n🔌 Adapter\n-------\nReal world example\n\u003e 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.\n\u003e 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.\n\u003e Yet another example would be a translator translating words spoken by one person to another\n\nIn plain words\n\u003e Adapter pattern lets you wrap an otherwise incompatible object in an adapter to make it compatible with another class.\n\nWikipedia says\n\u003e 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.\n\n**Programmatic Example**\n\nConsider a game where there is a hunter and he hunts lions.\n\nFirst we have an interface `Lion` that all types of lions have to implement\n\n```js\n/*\nLion interface :\n\nroar()\n*/\n\nclass AfricanLion  {\n    roar() {}\n}\n\nclass AsianLion  {\n    roar() {}\n}\n```\nAnd hunter expects any implementation of `Lion` interface to hunt.\n```js\nclass Hunter {\n    hunt(lion) {\n        // ... some code before\n        lion.roar()\n        //... some code after\n    }\n}\n```\n\nNow 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\n \n```js\n// This needs to be added to the game\nclass WildDog {\n    bark() {\n    }\n}\n\n// Adapter around wild dog to make it compatible with our game\nclass WildDogAdapter {\n\n    constructor(dog) {\n        this.dog = dog;\n    }\n    \n    roar() {\n        this.dog.bark();\n    }\n}\n```\nAnd now the `WildDog` can be used in our game using `WildDogAdapter`.\n\n```js\nwildDog = new WildDog()\nwildDogAdapter = new WildDogAdapter(wildDog)\n\nhunter = new Hunter()\nhunter.hunt(wildDogAdapter)\n```\n\n🚡 Bridge\n------\nReal world example\n\u003e 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.\n\n![With and without the bridge pattern](https://cloud.githubusercontent.com/assets/11269635/23065293/33b7aea0-f515-11e6-983f-98823c9845ee.png)\n\nIn Plain Words\n\u003e Bridge pattern is about preferring composition over inheritance. Implementation details are pushed from a hierarchy to another object with a separate hierarchy.\n\nWikipedia says\n\u003e 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\"\n\n**Programmatic Example**\n\nTranslating our WebPage example from above. Here we have the `WebPage` hierarchy\n\n```js\n/*\nWebpage interface :\n\nconstructor(theme)\ngetContent()\n*/\n\nclass About{ \n    constructor(theme) {\n        this.theme = theme\n    }\n    \n    getContent() {\n        return `About page in ${this.theme.getColor()}`\n    }\n}\n\nclass Careers{\n   constructor(theme) {\n       this.theme = theme\n   }\n   \n   getContent() {\n       return `Careers page in ${this.theme.getColor()}`\n   } \n}\n```\nAnd the separate theme hierarchy\n```js\n/*\nTheme interface :\n\ngetColor()\n*/\n\nclass DarkTheme{\n    getColor() {\n        return 'Dark Black'\n    }\n}\nclass LightTheme{\n    getColor() {\n        return 'Off white'\n    }\n}\nclass AquaTheme{\n    getColor() {\n        return 'Light blue'\n    }\n}\n```\nAnd both the hierarchies\n```js\nconst darkTheme = new DarkTheme()\n\nconst about = new About(darkTheme)\nconst careers = new Careers(darkTheme)\n\nconsole.log(about.getContent() )// \"About page in Dark Black\"\nconsole.log(careers.getContent() )// \"Careers page in Dark Black\"\n```\n\n🌿 Composite\n-----------------\n\nReal world example\n\u003e 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.\n\nIn plain words\n\u003e Composite pattern lets clients to treat the individual objects in a uniform manner.\n\nWikipedia says\n\u003e 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.\n\n**Programmatic Example**\n\nTaking our employees example from above. Here we have different employee types\n\n```js\n/*\nEmployee interface :\n\nconstructor(name, salary)\ngetName()\nsetSalary()\ngetSalary()\ngetRoles()\n*/\n\nclass Developer {\n\n    constructor(name, salary) {\n        this.name = name\n        this.salary = salary\n    }\n\n    getName() {\n        return this.name\n    }\n\n    setSalary(salary) {\n        this.salary = salary\n    }\n\n    getSalary() {\n        return this.salary\n    }\n\n    getRoles() {\n        return this.roles\n    }\n\n    develop() {\n        /* */\n    }\n}\n\nclass Designer {\n\n    constructor(name, salary) {\n        this.name = name\n        this.salary = salary\n    }\n\n    getName() {\n        return this.name\n    }\n\n    setSalary(salary) {\n        this.salary = salary\n    }\n\n    getSalary() {\n        return this.salary\n    }\n\n    getRoles() {\n        return this.roles\n    }\n\n    design() {\n        /* */\n    }\n}\n```\n\nThen we have an organization which consists of several different types of employees\n\n```js\nclass Organization {\n    constructor(){\n        this.employees = []\n    }\n\n    addEmployee(employee) {\n        this.employees.push(employee)\n    }\n\n    getNetSalaries() {\n        let netSalary = 0\n\n        this.employees.forEach(employee =\u003e {\n            netSalary += employee.getSalary()\n        })\n\n        return netSalary\n    }\n}\n```\n\nAnd then it can be used as\n\n```js\n// Prepare the employees\nconst john = new Developer('John Doe', 12000)\nconst jane = new Designer('Jane', 10000)\n\n// Add them to organization\nconst organization = new Organization()\norganization.addEmployee(john)\norganization.addEmployee(jane)\n\nconsole.log(\"Net salaries: \" , organization.getNetSalaries()) // Net Salaries: 22000\n```\n\n☕ Decorator\n-------------\n\nReal world example\n\n\u003e 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.\n\nIn plain words\n\u003e Decorator pattern lets you dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class.\n\nWikipedia says\n\u003e 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.\n\n**Programmatic Example**\n\nLets take coffee for example. First of all we have a simple coffee implementing the coffee interface\n\n```js\n/*\nCoffee interface:\ngetCost()\ngetDescription()\n*/\n\nclass SimpleCoffee{\n\n    getCost() {\n        return 10\n    }\n\n    getDescription() {\n        return 'Simple coffee'\n    }\n}\n```\nWe want to make the code extensible to allow options to modify it if required. Lets make some add-ons (decorators)\n```js\nclass MilkCoffee {\n\n\n    constructor(coffee) {\n        this.coffee = coffee\n    }\n\n    getCost() {\n        return this.coffee.getCost() + 2\n    }\n\n    getDescription() {\n        return `${this.coffee.getDescription()}, milk`\n    }\n}\n\nclass WhipCoffee {\n\n    constructor(coffee) {\n        this.coffee = coffee\n    }\n\n    getCost() {\n        return this.coffee.getCost() + 5\n    }\n\n    getDescription() {\n        return `${this.coffee.getDescription()}, whip`\n    }\n}\n\nclass VanillaCoffee {\n\n    constructor(coffee) {\n        this.coffee = coffee\n    }\n\n    getCost() {\n        return this.coffee.getCost() + 3\n    }\n\n    getDescription() {\n        return `${this.coffee.getDescription()}, vanilla`\n    }\n}\n\n```\n\nLets make a coffee now\n\n```js\nlet someCoffee\n\nsomeCoffee = new SimpleCoffee()\nconsole.log(someCoffee.getCost())// 10\nconsole.log(someCoffee.getDescription())// Simple Coffee\n\nsomeCoffee = new MilkCoffee(someCoffee)\nconsole.log(someCoffee.getCost())// 12\nconsole.log(someCoffee.getDescription())// Simple Coffee, milk\n\nsomeCoffee = new WhipCoffee(someCoffee)\nconsole.log(someCoffee.getCost())// 17\nconsole.log(someCoffee.getDescription())// Simple Coffee, milk, whip\n\nsomeCoffee = new VanillaCoffee(someCoffee)\nconsole.log(someCoffee.getCost())// 20\nconsole.log(someCoffee.getDescription())// Simple Coffee, milk, whip, vanilla\n```\n\n📦 Facade\n----------------\n\nReal world example\n\u003e 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.\n\nIn plain words\n\u003e Facade pattern provides a simplified interface to a complex subsystem.\n\nWikipedia says\n\u003e A facade is an object that provides a simplified interface to a larger body of code, such as a class library.\n\n**Programmatic Example**\nTaking our computer example from above. Here we have the computer class\n\n```js\nclass Computer {\n\n    getElectricShock() {\n        console.log('Ouch!')\n    }\n\n    makeSound() {\n        console.log('Beep beep!')\n    }\n\n    showLoadingScreen() {\n        console.log('Loading..')\n    }\n\n    bam() {\n        console.log('Ready to be used!')\n    }\n\n    closeEverything() {\n        console.log('Bup bup bup buzzzz!')\n    }\n\n    sooth() {\n        console.log('Zzzzz')\n    }\n\n    pullCurrent() {\n        console.log('Haaah!')\n    }\n}\n```\nHere we have the facade\n```js\nclass ComputerFacade\n{\n    constructor(computer) {\n        this.computer = computer\n    }\n\n    turnOn() {\n        this.computer.getElectricShock()\n        this.computer.makeSound()\n        this.computer.showLoadingScreen()\n        this.computer.bam()\n    }\n\n    turnOff() {\n        this.computer.closeEverything()\n        this.computer.pullCurrent()\n        this.computer.sooth()\n    }\n}\n```\nNow to use the facade\n```js\nconst computer = new ComputerFacade(new Computer())\ncomputer.turnOn() // Ouch! Beep beep! Loading.. Ready to be used!\ncomputer.turnOff() // Bup bup buzzz! Haah! Zzzzz\n```\n\n🍃 Flyweight\n---------\n\nReal world example\n\u003e 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.\n\nIn plain words\n\u003e It is used to minimize memory usage or computational expenses by sharing as much as possible with similar objects.\n\nWikipedia says\n\u003e 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.\n\n**Programmatic example**\nTranslating our tea example from above. First of all we have tea types and tea maker\n\n```js\n// Anything that will be cached is flyweight. \n// Types of tea here will be flyweights.\nclass KarakTea {\n}\n\n// Acts as a factory and saves the tea\nclass TeaMaker {\n    constructor(){\n        this.availableTea = {}\n    }\n\n    make(preference) {\n        this.availableTea[preference] = this.availableTea[preference] || (new KarakTea())\n        return this.availableTea[preference]\n    }\n}\n```\n\nThen we have the `TeaShop` which takes orders and serves them\n\n```js\nclass TeaShop {\n    constructor(teaMaker) {\n        this.teaMaker = teaMaker\n        this.orders = []\n    }\n\n    takeOrder(teaType, table) {\n        this.orders[table] = this.teaMaker.make(teaType)\n    }\n\n    serve() {\n        this.orders.forEach((order, index) =\u003e {\n            console.log(`Serving tea to table# ${index}`)\n        })\n    }\n}\n```\nAnd it can be used as below\n\n```js\nconst teaMaker = new TeaMaker()\nconst shop = new TeaShop(teaMaker)\n\nshop.takeOrder('less sugar', 1)\nshop.takeOrder('more milk', 2)\nshop.takeOrder('without sugar', 5)\n\nshop.serve()\n// Serving tea to table# 1\n// Serving tea to table# 2\n// Serving tea to table# 5\n```\n\n🎱 Proxy\n-------------------\nReal world example\n\u003e 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.\n\nIn plain words\n\u003e Using the proxy pattern, a class represents the functionality of another class.\n\nWikipedia says\n\u003e 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.\n\n**Programmatic Example**\nTaking our security door example from above. Firstly we have the door interface and an implementation of door\n\n```js\n/*\nDoor interface :\n\nopen()\nclose()\n*/\n\nclass LabDoor {\n    open() {\n        console.log('Opening lab door')\n    }\n\n    close() {\n        console.log('Closing the lab door')\n    }\n}\n```\nThen we have a proxy to secure any doors that we want\n```js\nclass Security {\n    constructor(door) {\n        this.door = door\n    }\n\n    open(password) {\n        if (this.authenticate(password)) {\n            this.door.open()\n        } else {\n        \tconsole.log('Big no! It ain\\'t possible.')\n        }\n    }\n\n    authenticate(password) {\n        return password === 'ecr@t'\n    }\n\n    close() {\n        this.door.close()\n    }\n}\n```\nAnd here is how it can be used\n```js\nconst door = new Security(new LabDoor())\ndoor.open('invalid') // Big no! It ain't possible.\n\ndoor.open('ecr@t') // Opening lab door\ndoor.close() // Closing lab door\n```\n\nBehavioral Design Patterns\n==========================\n\nIn plain words\n\u003e 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?\"\n\nWikipedia says\n\u003e 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.\n\n* [Chain of Responsibility](#-chain-of-responsibility)\n* [Command](#-command)\n* [Iterator](#-iterator)\n* [Mediator](#-mediator)\n* [Memento](#-memento)\n* [Observer](#-observer)\n* [Visitor](#-visitor)\n* [Strategy](#-strategy)\n* [State](#-state)\n* [Template Method](#-template-method)\n\n🔗 Chain of Responsibility\n-----------------------\n\nReal world example\n\u003e 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.\n\nIn plain words\n\u003e 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.\n\nWikipedia says\n\u003e 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.\n\n**Programmatic Example**\n\nTranslating our account example above. First of all we have a base account having the logic for chaining the accounts together and some accounts\n\n```js\nclass Account {\n\n    setNext(account) {\n        this.successor = account\n    }\n    \n    pay(amountToPay) {\n        if (this.canPay(amountToPay)) {\n            console.log(`Paid ${amountToPay} using ${this.name}`)\n        } else if (this.successor) {\n            console.log(`Cannot pay using ${this.name}. Proceeding...`)\n            this.successor.pay(amountToPay)\n        } else {\n            console.log('None of the accounts have enough balance')\n        }\n    }\n    \n    canPay(amount) {\n        return this.balance \u003e= amount\n    }\n}\n\nclass Bank extends Account {\n    constructor(balance) {\n        super()\n        this.name = 'bank'\n        this.balance = balance\n    }\n}\n\nclass Paypal extends Account {\n    constructor(balance) {\n        super()        \n        this.name = 'Paypal'\n        this.balance = balance\n    }\n}\n\nclass Bitcoin extends Account {\n    constructor(balance) {\n        super()        \n        this.name = 'bitcoin'\n        this.balance = balance\n    }\n}\n```\n\nNow let's prepare the chain using the links defined above (i.e. Bank, Paypal, Bitcoin)\n\n```js\n// Let's prepare a chain like below\n//      bank.paypal.bitcoin\n//\n// First priority bank\n//      If bank can't pay then paypal\n//      If paypal can't pay then bit coin\n\nconst bank = new Bank(100)          // Bank with balance 100\nconst paypal = new Paypal(200)      // Paypal with balance 200\nconst bitcoin = new Bitcoin(300)    // Bitcoin with balance 300\n\nbank.setNext(paypal)\npaypal.setNext(bitcoin)\n\n// Let's try to pay using the first priority i.e. bank\nbank.pay(259)\n\n// Output will be\n// ==============\n// Cannot pay using bank. Proceeding ..\n// Cannot pay using paypal. Proceeding ..: \n// Paid 259 using Bitcoin!\n```\n\n👮 Command\n-------\n\nReal world example\n\u003e 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. \n\u003e Another example would be you (i.e. `Client`) switching on (i.e. `Command`) the television (i.e. `Receiver`) using a remote control (`Invoker`).\n\nIn plain words\n\u003e Allows you to encapsulate actions in objects. The key idea behind this pattern is to provide the means to decouple client from receiver.\n\nWikipedia says\n\u003e 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.\n\n**Programmatic Example**\n\nFirst of all we have the receiver that has the implementation of every action that could be performed\n```js\n// Receiver\nclass Bulb {\n    turnOn() {\n        console.log('Bulb has been lit')\n    }\n    \n    turnOff() {\n        console.log('Darkness!')\n    }\n}\n```\nthen we have an interface that each of the commands are going to implement and then we have a set of commands\n```js\n/*\nCommand interface :\n\n    execute()\n    undo()\n    redo()\n*/\n\n// Command\nclass TurnOnCommand {\n    constructor(bulb) {\n        this.bulb = bulb\n    }\n    \n    execute() {\n        this.bulb.turnOn()\n    }\n    \n    undo() {\n        this.bulb.turnOff()\n    }\n    \n    redo() {\n        this.execute()\n    }\n}\n\nclass TurnOffCommand {\n    constructor(bulb) {\n        this.bulb = bulb\n    }\n    \n    execute() {\n        this.bulb.turnOff()\n    }\n    \n    undo() {\n        this.bulb.turnOn()\n    }\n    \n    redo() {\n        this.execute()\n    }\n}\n```\nThen we have an `Invoker` with whom the client will interact to process any commands\n```js\n// Invoker\nclass RemoteControl {\n    submit(command) {\n        command.execute()\n    }\n}\n```\nFinally let's see how we can use it in our client\n```js\nconst bulb = new Bulb()\n\nconst turnOn = new TurnOnCommand(bulb)\nconst turnOff = new TurnOffCommand(bulb)\n\nconst remote = new RemoteControl()\nremote.submit(turnOn) // Bulb has been lit!\nremote.submit(turnOff) // Darkness!\n```\n\nCommand 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. \n\n➿ Iterator\n--------\n\nReal world example\n\u003e 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.  \n\nIn plain words\n\u003e It presents a way to access the elements of an object without exposing the underlying presentation.\n\nWikipedia says\n\u003e 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.\n\n**Programmatic example**\n Translating our radio stations example from above. First of all we have `RadioStation`\n\n```js\nclass RadioStation {\n    constructor(frequency) {\n        this.frequency = frequency    \n    }\n    \n    getFrequency() {\n        return this.frequency\n    }\n}\n```\nThen we have our iterator\n\n```js\nclass StationList {\n    constructor(){\n        this.stations = []\n    }\n\n    addStation(station) {\n        this.stations.push(station)\n    }\n    \n    removeStation(toRemove) {\n        const toRemoveFrequency = toRemove.getFrequency()\n        this.stations = this.stations.filter(station =\u003e {\n            return station.getFrequency() !== toRemoveFrequency\n        })\n    }\n}\n```\nAnd then it can be used as\n```js\nconst stationList = new StationList()\n\nstationList.addStation(new RadioStation(89))\nstationList.addStation(new RadioStation(101))\nstationList.addStation(new RadioStation(102))\nstationList.addStation(new RadioStation(103.2))\n\nstationList.stations.forEach(station =\u003e console.log(station.getFrequency()))\n\nstationList.removeStation(new RadioStation(89)) // Will remove station 89\n```\n\n👽 Mediator\n========\n\nReal world example\n\u003e 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. \n\nIn plain words\n\u003e 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. \n\nWikipedia says\n\u003e 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.\n\n**Programmatic Example**\n\nHere is the simplest example of a chat room (i.e. mediator) with users (i.e. colleagues) sending messages to each other. \n\nFirst of all, we have the mediator i.e. the chat room \n\n```js\n// Mediator\nclass ChatRoom {\n    showMessage(user, message) {\n        const time = new Date()\n        const sender = user.getName()\n\n        console.log(`${time}[${sender}]: ${message}`)\n    }\n}\n```\n\nThen we have our users i.e. colleagues\n```js\nclass User {\n    constructor(name, chatMediator) {\n        this.name = name\n        this.chatMediator = chatMediator\n    }\n    \n    getName() {\n        return this.name\n    }\n    \n    send(message) {\n        this.chatMediator.showMessage(this, message)\n    }\n}\n```\nAnd the usage\n```js\nconst mediator = new ChatRoom()\n\nconst john = new User('John Doe', mediator)\nconst jane = new User('Jane Doe', mediator)\n\njohn.send('Hi there!')\njane.send('Hey!')\n\n// Output will be\n// Feb 14, 10:58 [John]: Hi there!\n// Feb 14, 10:58 [Jane]: Hey!\n```\n\n💾 Memento\n-------\nReal world example\n\u003e 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). \n\nIn plain words\n\u003e 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.\n\nWikipedia says\n\u003e The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).\n\nUsually useful when you need to provide some sort of undo functionality.\n\n**Programmatic Example**\n\nLets take an example of text editor which keeps saving the state from time to time and that you can restore if you want.\n\nFirst of all we have our memento object that will be able to hold the editor state\n\n```js\nclass EditorMemento {\n    constructor(content) {\n        this._content = content\n    }\n    \n    getContent() {\n        return this._content\n    }\n}\n```\n\nThen we have our editor i.e. originator that is going to use memento object\n\n```js\nclass Editor {\n    constructor(){\n        this._content = ''\n    }\n    \n    type(words) {\n        this._content += ` ${words}`\n    }\n    \n    getContent() {\n        return this._content\n    }\n    \n    save() {\n        return new EditorMemento(this._content)\n    }\n    \n    restore(memento) {\n        this._content = memento.getContent()\n    }\n}\n```\n\nAnd then it can be used as \n\n```js\nconst editor = new Editor()\n\n// Type some stuff\neditor.type('This is the first sentence.')\neditor.type('This is second.')\n\n// Save the state to restore to : This is the first sentence. This is second.\nconst saved = editor.save()\n\n// Type some more\neditor.type('And this is third.')\n\n// Output: Content before Saving\nconsole.log(editor.getContent())// This is the first sentence. This is second. And this is third.\n\n// Restoring to last saved state\neditor.restore(saved)\n\nconsole.log(editor.getContent()) // This is the first sentence. This is second.\n```\n\n😎 Observer\n--------\n\n(Otherwise known as _\"pub-sub\"_)\n\nReal world example\n\u003e 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.   \n\nIn plain words\n\u003e Defines a dependency between objects so that whenever an object changes its state, all its dependents are notified.\n\nWikipedia says\n\u003e 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.\n\n**Programmatic example**\n\nTranslating our example from above. First of all we have job seekers that need to be notified for a job posting\n```js\nconst JobPost = title =\u003e ({\n    title: title\n})\n\nclass JobSeeker {\n    constructor(name) {\n        this._name = name\n    }\n\n    notify(jobPost) {\n        console.log(this._name, 'has been notified of a new posting :', jobPost.title)\n    }\n}\n```\nThen we have our job postings to which the job seekers will subscribe\n```js\nclass JobBoard {\n    constructor() {\n        this._subscribers = []\n    }\n\n    subscribe(jobSeeker) {\n        this._subscribers.push(jobSeeker)\n    }\n\n    addJob(jobPosting) {\n        this._subscribers.forEach(subscriber =\u003e {\n            subscriber.notify(jobPosting)\n        })\n    }\n}\n```\nThen it can be used as\n```js\n// Create subscribers\nconst jonDoe = new JobSeeker('John Doe')\nconst janeDoe = new JobSeeker('Jane Doe')\nconst kaneDoe = new JobSeeker('Kane Doe')\n\n// Create publisher and attach subscribers\nconst jobBoard = new JobBoard()\njobBoard.subscribe(jonDoe)\njobBoard.subscribe(janeDoe)\n\n// Add a new job and see if subscribers get notified\njobBoard.addJob(JobPost('Software Engineer'))\n\n// Output\n// John Doe has been notified of a new posting : Software Engineer\n// Jane Doe has been notified of a new posting : Software Engineer\n```\n\n🏃 Visitor\n-------\nReal world example\n\u003e 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.\n\nIn plain words\n\u003e Visitor pattern let's you add further operations to objects without having to modify them.\n    \nWikipedia says\n\u003e 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.\n\n**Programmatic example**\n\nLet'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 \n\nWe have our implementations for the animals\n```js\nclass Monkey {\n    shout() {\n        console.log('Ooh oo aa aa!')\n    }\n\n    accept(operation) {\n        operation.visitMonkey(this)\n    }\n}\n\nclass Lion {\n    roar() {\n        console.log('Roaaar!')\n    }\n    \n    accept(operation) {\n        operation.visitLion(this)\n    }\n}\n\nclass Dolphin {\n    speak() {\n        console.log('Tuut tuttu tuutt!')\n    }\n    \n    accept(operation) {\n        operation.visitDolphin(this)\n    }\n}\n```\nLet's implement our visitor\n```js\nconst speak = {\n    visitMonkey(monkey){\n        monkey.shout()\n    },\n    visitLion(lion){\n        lion.roar()\n    },\n    visitDolphin(dolphin){\n        dolphin.speak()\n    }\n}\n```\n\nAnd then it can be used as\n```js\nconst monkey = new Monkey()\nconst lion = new Lion()\nconst dolphin = new Dolphin()\n\nmonkey.accept(speak)    // Ooh oo aa aa!    \nlion.accept(speak)      // Roaaar!\ndolphin.accept(speak)   // Tuut tutt tuutt!\n```\nWe 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.\n\n```js\nconst jump = {\n    visitMonkey(monkey) {\n        console.log('Jumped 20 feet high! on to the tree!')\n    },\n    visitLion(lion) {\n        console.log('Jumped 7 feet! Back on the ground!')\n    },\n    visitDolphin(dolphin) {\n        console.log('Walked on water a little and disappeared')\n    }\n}\n```\nAnd for the usage\n```js\nmonkey.accept(speak)   // Ooh oo aa aa!\nmonkey.accept(jump)    // Jumped 20 feet high! on to the tree!\n\nlion.accept(speak)     // Roaaar!\nlion.accept(jump)      // Jumped 7 feet! Back on the ground! \n\ndolphin.accept(speak)  // Tuut tutt tuutt! \ndolphin.accept(jump)   // Walked on water a little and disappeared\n```\n\n💡 Strategy\n--------\n\nReal world example\n\u003e 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.\n\nIn plain words\n\u003e Strategy pattern allows you to switch the algorithm or strategy based upon the situation.\n\nWikipedia says\n\u003e 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.\n \n**Programmatic example**\n\nTranslating our example from above, we can easily implement this strategy in javascript using its feature of first class functions.\n\n```js\nconst bubbleSort = dataset =\u003e {\n    console.log('Sorting with bubble sort')\n    // ...\n    // ...\n    return dataset\n}\n\nconst quickSort = dataset =\u003e {\n    console.log('Sorting with quick sort')\n    // ...\n    // ...\n    return dataset\n}\n```\n \nAnd then we have our client that is going to use any strategy\n```js\nconst sorter = dataset =\u003e {\n    if(dataset.length \u003e 5){\n        return quickSort\n    } else {\n        return bubbleSort\n    }\n}\n```\nAnd it can be used as\n```js\nconst longDataSet = [1, 5, 4, 3, 2, 8]\nconst shortDataSet = [1, 5, 4]\n\nconst sorter1 = sorter(longDataSet)\nconst sorter2 = sorter(shortDataSet)\n\nsorter1(longDataSet) // Output : Sorting with quick sort\nsorter2(shortDataSet) // Output : Sorting with bubble sort\n```\n\n💢 State\n-----\nReal world example\n\u003e 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.  \n\nIn plain words\n\u003e It lets you change the behavior of a class when the state changes.\n\nWikipedia says\n\u003e 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.\n\u003e 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\n\n**Programmatic example**\n\nLet'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.\n\nFirst of all we have our transformation functions\n\n```js\nconst upperCase = inputString =\u003e inputString.toUpperCase()\nconst lowerCase = inputString =\u003e inputString.toLowerCase()\nconst defaultTransform = inputString =\u003e inputString\n```\nThen we have our editor\n```js\nclass TextEditor {\n    constructor(transform) {\n        this._transform = transform\n    }\n    \n    setTransform(transform) {\n        this._transform = transform\n    }\n    \n    type(words) {\n        console.log(this._transform(words))\n    }\n}\n```\nAnd then it can be used as\n```js\nconst editor = new TextEditor(defaultTransform)\n\neditor.type('First line')\n\neditor.setTransform(upperCase)\n\neditor.type('Second line')\neditor.type('Third line')\n\neditor.setTransform(lowerCase)\n\neditor.type('Fourth line')\neditor.type('Fifth line')\n\n// Output:\n// First line\n// SECOND LINE\n// THIRD LINE\n// fourth line\n// fifth line\n```\n\n📒 Template Method\n---------------\n\nReal world example\n\u003e Suppose we are getting some house built. The steps for building might look like \n\u003e - Prepare the base of house\n\u003e - Build the walls\n\u003e - Add roof\n\u003e - Add other floors\n\u003e 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.\n  \nIn plain words\n\u003e Template method defines the skeleton of how certain algorithm could be performed but defers the implementation of those steps to the children classes.\n \nWikipedia says\n\u003e 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.\n\n**Programmatic Example**\n\nImagine 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.\n\nFirst of all we have our base class that specifies the skeleton for the build algorithm\n```js\nclass Builder {\n    // Template method \n    build() {\n        this.test()\n        this.lint()\n        this.assemble()\n        this.deploy()\n    }\n}\n```\n\nThen we can have our implementations\n\n```js\nclass AndroidBuilder extends Builder {\n    test() {\n        console.log('Running android tests')\n    }\n    \n    lint() {\n        console.log('Linting the android code')\n    }\n    \n    assemble() {\n        console.log('Assembling the android build')\n    }\n    \n    deploy() {\n        console.log('Deploying android build to server')\n    }\n}\n\nclass IosBuilder extends Builder {\n    test() {\n        console.log('Running ios tests')\n    }\n    \n    lint() {\n        console.log('Linting the ios code')\n    }\n    \n    assemble() {\n        console.log('Assembling the ios build')\n    }\n    \n    deploy() {\n        console.log('Deploying ios build to server')\n    }\n}\n```\nAnd then it can be used as\n\n```js\nconst androidBuilder = new AndroidBuilder()\nandroidBuilder.build()\n\n// Output:\n// Running android tests\n// Linting the android code\n// Assembling the android build\n// Deploying android build to server\n\nconst iosBuilder = new IosBuilder()\niosBuilder.build()\n\n// Output:\n// Running ios tests\n// Linting the ios code\n// Assembling the ios build\n// Deploying ios build to server\n```\n\n## 🚦 Wrap Up Folks\n\nAnd 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.\n\n## 👬 Contribution\n\n- Report issues\n- Open pull request with improvements\n- Spread the word\n\n## License\nMIT © [Soham Kamani](http://sohamkamani.com)\nBased on [\"Design patterns for humans\"](https://github.com/kamranahmedse/design-patterns-for-humans) Copyright 2017 Kamran Ahmed\n","funding_links":[],"categories":["Programming Language Design Patterns","Categories","miscellaneous","Others","Web Development","JavaScript \u003ca name=\"js\"\u003e\u003c/a\u003e","JavaScript","GoF design patterns (Language/Framework specifc)","二、按编程语言分的核心设计模式","Language/Framework design patterns (mainly GoF)"],"sub_categories":["**JavaScript/TypeScript**"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsohamkamani%2Fjavascript-design-patterns-for-humans","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsohamkamani%2Fjavascript-design-patterns-for-humans","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsohamkamani%2Fjavascript-design-patterns-for-humans/lists"}