{"id":54,"date":"2020-04-22T15:07:09","date_gmt":"2020-04-22T15:07:09","guid":{"rendered":"https:\/\/cebucodesolutions.com\/blog\/?p=54"},"modified":"2020-04-22T15:07:12","modified_gmt":"2020-04-22T15:07:12","slug":"javascript-design-patterns","status":"publish","type":"post","link":"https:\/\/cebucodesolutions.com\/blog\/2020\/04\/22\/javascript-design-patterns\/","title":{"rendered":"JavaScript Design Patterns"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">The ultimate guide to the most useful design patterns<\/h2>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"772\" height=\"375\" src=\"https:\/\/cebucodesolutions.com\/blog\/wp-content\/uploads\/2020\/04\/js.jpeg\" alt=\"\" class=\"wp-image-55\" srcset=\"https:\/\/cebucodesolutions.com\/blog\/wp-content\/uploads\/2020\/04\/js.jpeg 772w, https:\/\/cebucodesolutions.com\/blog\/wp-content\/uploads\/2020\/04\/js-300x146.jpeg 300w, https:\/\/cebucodesolutions.com\/blog\/wp-content\/uploads\/2020\/04\/js-768x373.jpeg 768w\" sizes=\"auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px\" \/><\/figure>\n\n\n\n<p><strong>UPDATE NOTE:<\/strong> Updated the Proxy Pattern example to use ES6 Proxy and Reflect. Replaced images of source code snippets with <strong>GitHub<\/strong> gists. <\/p>\n\n\n\n<p>In\n this article, we are going to talk about design patterns that can be \nand should be used to write better, maintainable JavaScript code. I \nassume you have a basic understanding of JavaScript and concepts like \nclasses (classes in JavaScript can be tricky), objects, prototypal \ninheritance, closures, etc.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p>This  article is a long read as a whole because of the nature of the subject  matter, so I have tried to keep the sections self-contained. So you as a  reader can pick and choose specific parts (or, in this case, specific  patterns) and ignore the ones you are not interested in or are well  versed with. Now, let\u2019s get started.<\/p>\n\n\n\n<p><strong>Note:<\/strong> Source code for the implementation of all the design patterns explained here is on <a rel=\"noreferrer noopener\" href=\"https:\/\/github.com\/drenther\/js-design-patterns\" target=\"_blank\"><strong>GitHub<\/strong><\/a>. <\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"f891\">Introduction<\/h1>\n\n\n\n<p>We  write code to solve problems. These problems usually have many  similarities, and, when trying to solve them, we notice several common  patterns. This is where design patterns come in.<\/p>\n\n\n\n<p> A <strong>design pattern<\/strong> is a term used in software engineering for a general, reusable solution to a commonly occurring problem in software design. <\/p>\n\n\n\n<p> The underlying concept of design patterns has been around in the  software engineering industry since the very beginning, but they weren\u2019t  really so formalised. <a rel=\"noreferrer noopener\" href=\"https:\/\/en.wikipedia.org\/wiki\/Design_Patterns\" target=\"_blank\"><strong>Design Patterns: Elements Of Reusable Object-Oriented Software<\/strong><\/a> written by <strong>Erich Gamma, Richard Helm, Ralph Johnson<\/strong>,and<strong> John Vlissides<\/strong>  \u2014 the famous Gang of Four (GoF)\u2014was instrumental in pushing the  formalised concept of design patterns in software engineering. Now,  design patterns are an essential part of software development and have  been so for a long time. <\/p>\n\n\n\n<p> There were 23 design patterns introduced in the original book. <\/p>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"552\" height=\"235\" src=\"https:\/\/cebucodesolutions.com\/blog\/wp-content\/uploads\/2020\/04\/1-wPH4aXJ_Arv4jnliLUySyQ.png\" alt=\"\" class=\"wp-image-56\" srcset=\"https:\/\/cebucodesolutions.com\/blog\/wp-content\/uploads\/2020\/04\/1-wPH4aXJ_Arv4jnliLUySyQ.png 552w, https:\/\/cebucodesolutions.com\/blog\/wp-content\/uploads\/2020\/04\/1-wPH4aXJ_Arv4jnliLUySyQ-300x128.png 300w\" sizes=\"auto, (max-width: 552px) 85vw, 552px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"552\" height=\"335\" src=\"https:\/\/cebucodesolutions.com\/blog\/wp-content\/uploads\/2020\/04\/1-pD3iU_fQx56oDlIMMBnbNw.png\" alt=\"\" class=\"wp-image-57\" srcset=\"https:\/\/cebucodesolutions.com\/blog\/wp-content\/uploads\/2020\/04\/1-pD3iU_fQx56oDlIMMBnbNw.png 552w, https:\/\/cebucodesolutions.com\/blog\/wp-content\/uploads\/2020\/04\/1-pD3iU_fQx56oDlIMMBnbNw-300x182.png 300w\" sizes=\"auto, (max-width: 552px) 85vw, 552px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"673\" height=\"556\" src=\"https:\/\/cebucodesolutions.com\/blog\/wp-content\/uploads\/2020\/04\/1-weYSJ2_ZxVY8yZ8reEGq6g.png\" alt=\"\" class=\"wp-image-58\" srcset=\"https:\/\/cebucodesolutions.com\/blog\/wp-content\/uploads\/2020\/04\/1-weYSJ2_ZxVY8yZ8reEGq6g.png 673w, https:\/\/cebucodesolutions.com\/blog\/wp-content\/uploads\/2020\/04\/1-weYSJ2_ZxVY8yZ8reEGq6g-300x248.png 300w\" sizes=\"auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px\" \/><\/figure>\n\n\n\n<p>Design\n patterns are beneficial for various reasons. They are proven solutions \nthat industry veterans have tried and tested. They are solid approaches \nthat solve issues in a widely accepted way and reflect the experience \nand insights of the industry-leading developers that helped define them.\n Patterns also make your code more reusable and readable while speeding \nup the development process vastly.<\/p>\n\n\n\n<p>Design patterns are by no means finished solutions. They only provide us with approaches or schemes to solve a problem.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p><strong>Note:<\/strong>\n In this article, we will mainly talk about design patterns from an \nobject-oriented point of view and in the context of their usability in \nmodern JavaScript. That is why many classic patterns from GoF may be \nomitted, and some modern patterns from sources like <a href=\"https:\/\/addyosmani.com\/resources\/essentialjsdesignpatterns\/book\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Addy Osmani\u2019s Learn JavaScript Design Patterns<\/strong><\/a>\n will be included. The examples are kept simple for easier understanding\n and are hence not the most optimised implementation of their respective\n design patterns.<\/p><\/blockquote>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"b607\">Categories of Design Patterns<\/h1>\n\n\n\n<p>Design patterns are usually categorized into three major groups.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1b00\">Creational Design Patterns<\/h2>\n\n\n\n<p>As\n the name suggests, these patterns are for handling object creational \nmechanisms. A creational design pattern basically solves a problem by \ncontrolling the creation process of an object.<\/p>\n\n\n\n<p>We will discuss the following patterns in detail: <strong><em>Constructor Pattern, Factory Pattern, Prototype Pattern, <\/em><\/strong>and <strong><em>Singleton Pattern.<\/em><\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"22d6\">Structural Design Patterns<\/h2>\n\n\n\n<p>These  patterns are concerned with class and object composition. They help  structure or restructure one or more parts without affecting the entire  system. In other words, they help obtain new functionalities without  tampering with the existing ones.<\/p>\n\n\n\n<p>We will discuss the following patterns in detail: <strong><em>Adapter Pattern, Composite Pattern, Decorator Pattern, Fa\u00e7ade Pattern, Flyweight Pattern, <\/em><\/strong>and <strong><em>Proxy Pattern.<\/em><\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6e03\">Behavioral Design Patterns<\/h2>\n\n\n\n<p>These patterns are concerned with improving communication between dissimilar objects.<\/p>\n\n\n\n<p>We will discuss the following patterns in detail: <strong><em>Chain  of Responsibility Pattern, Command Pattern, Iterator Pattern, Mediator  Pattern, Observer Pattern, State Pattern, Strategy Pattern, <\/em><\/strong>and <strong><em>Template Pattern.<\/em><\/strong><\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"2d15\">Constructor Pattern<\/h1>\n\n\n\n<p>This\n is a class-based creational design pattern. Constructors are special \nfunctions that can be used to instantiate new objects with methods and \nproperties defined by that function.<\/p>\n\n\n\n<p>It\n is not one of the classic design patterns. In fact, it is more of a \nbasic language construct than a pattern in most object-oriented \nlanguages. But in JavaScript, objects can be created on the fly without \nany constructor functions or \u201cclass\u201d definition. Therefore, I think it \nis important to lay down the foundation for other patterns to come with \nthis simple one.<\/p>\n\n\n\n<p>Constructor pattern is one of the most commonly used patterns in JavaScript for creating new objects of a given kind.<\/p>\n\n\n\n<p>In this example, we define a <code>Hero<\/code> class with attributes like <code>name<\/code> and <code>specialAbility<\/code> and methods like <code>getDetails<\/code>. Then, we instantiate an object <code>IronMan<\/code> by invoking the constructor method with the <code>new<\/code> keyword passing in the values for the respective attributes as arguments.<\/p>\n\n\n\n<p>\/\/ traditional Function-based syntax<br>\nfunction Hero(name, specialAbility) {<br>\n  \/\/ setting property values<br>\n  this.name = name;<br>\n  this.specialAbility = specialAbility;<\/p>\n\n\n\n<p>\/\/ declaring a method on the object<br>\n  this.getDetails = function() {<br>\n    return this.name + &#8216; can &#8216; + this.specialAbility;<br>\n  };<br>\n}<\/p>\n\n\n\n<p>\/\/ ES6 Class syntax<br>\nclass Hero {<br>\n  constructor(name, specialAbility) {<br>\n    \/\/ setting property values<br>\n    this._name = name;<br>\n    this._specialAbility = specialAbility;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ declaring a method on the object\nthis.getDetails = function() {\n  return `${this._name} can ${this._specialAbility}`;\n};<\/code><\/pre>\n\n\n\n<p>}<br>\n}<\/p>\n\n\n\n<p>\/\/ creating new instances of Hero<br>\nconst IronMan = new Hero(&#8216;Iron Man&#8217;, &#8216;fly&#8217;);<\/p>\n\n\n\n<p>console.log(IronMan.getDetails()); \/\/ Iron Man can fly<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"2f2e\">Factory Pattern<\/h1>\n\n\n\n<p>Factory\n pattern is another class-based creational pattern. In this, we provide a\n generic interface that delegates the responsibility of object \ninstantiation to its subclasses.<\/p>\n\n\n\n<p>This\n pattern is frequently used when we need to manage or manipulate \ncollections of objects that are different yet have many similar \ncharacteristics.<\/p>\n\n\n\n<p>In this example, we create a factory class named <code>BallFactory<\/code>  that has a method that takes in parameters, and, depending on the  parameters, it delegates the object instantiation responsibility to the  respective class. If the type parameter is <code>\"football\"<\/code> or <code>\"soccer\"<\/code> object instantiation is handled by <code>Football<\/code> class, but if it is <code>\"basketball\"<\/code> object instantiation is handled by <code>Basketball<\/code> class.<\/p>\n\n\n\n<p>class BallFactory {<br>\n  constructor() {<br>\n    this.createBall = function(type) {<br>\n      let ball;<br>\n      if (type === &#8216;football&#8217; || type === &#8216;soccer&#8217;) ball = new Football();<br>\n      else if (type === &#8216;basketball&#8217;) ball = new Basketball();<br>\n      ball.roll = function() {<br>\n        return <code>The ${this._type} is rolling.<\/code>;<br>\n      };<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  return ball;\n};<\/code><\/pre>\n\n\n\n<p>}<br>\n}<\/p>\n\n\n\n<p>class Football {<br>\n  constructor() {<br>\n    this._type = &#8216;football&#8217;;<br>\n    this.kick = function() {<br>\n      return &#8216;You kicked the football.&#8217;;<br>\n    };<br>\n  }<br>\n}<\/p>\n\n\n\n<p>class Basketball {<br>\n  constructor() {<br>\n    this._type = &#8216;basketball&#8217;;<br>\n    this.bounce = function() {<br>\n      return &#8216;You bounced the basketball.&#8217;;<br>\n    };<br>\n  }<br>\n}<\/p>\n\n\n\n<p>\/\/ creating objects<br>\nconst factory = new BallFactory();<\/p>\n\n\n\n<p>const myFootball = factory.createBall(&#8216;football&#8217;);<br>\nconst myBasketball = factory.createBall(&#8216;basketball&#8217;);<\/p>\n\n\n\n<p>console.log(myFootball.roll()); \/\/ The football is rolling.<br> console.log(myBasketball.roll()); \/\/ The basketball is rolling.<br> console.log(myFootball.kick()); \/\/ You kicked the football.<br> console.log(myBasketball.bounce()); \/\/ You bounced the basketball.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"4fdb\">Prototype Pattern<\/h1>\n\n\n\n<p>This\n pattern is an object-based creational design pattern. In this, we use a\n sort of a \u201cskeleton\u201d of an existing object to create or instantiate new\n objects.<\/p>\n\n\n\n<p>This\n pattern is specifically important and beneficial to JavaScript because \nit utilizes prototypal inheritance instead of a classic object-oriented \ninheritance. Hence, it plays to JavaScript\u2019s strength and has native \nsupport.<\/p>\n\n\n\n<p>In this example, we have a <code>car<\/code> object that we use as the prototype to create another object <code>myCar<\/code> with JavaScript\u2019s <code>Object.create <\/code>feature and define an extra property <code>owner<\/code> on the new object.<\/p>\n\n\n\n<p>\/\/ using Object.create as was recommended by ES5 standard<br>\nconst car = {<br>\n  noOfWheels: 4,<br>\n  start() {<br>\n    return &#8216;started&#8217;;<br>\n  },<br>\n  stop() {<br>\n    return &#8216;stopped&#8217;;<br>\n  },<br>\n};<\/p>\n\n\n\n<p>\/\/ Object.create(proto[, propertiesObject])<\/p>\n\n\n\n<p>const myCar = Object.create(car, { owner: { value: &#8216;John&#8217; } });<\/p>\n\n\n\n<p>console.log(myCar.<strong>proto<\/strong> === car); \/\/ true<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"5c2d\">Singleton Pattern<\/h1>\n\n\n\n<p>Singleton\n is a special creational design pattern in which only one instance of a \nclass can exist. It works like this \u2014 if no instance of the singleton \nclass exists then a new instance is created and returned, but if an \ninstance already exists, then the reference to the existing instance is \nreturned.<\/p>\n\n\n\n<p>A perfect real-life example would be that of <code>mongoose<\/code> (the famous Node.js ODM library for MongoDB). It utilizes the singleton pattern.<\/p>\n\n\n\n<p>In this example, we have a <code>Database<\/code> class that is a singleton. First, we create an object <code>mongo<\/code> by using the <code>new<\/code> operator to invoke the <code>Database<\/code> class constructor. This time an object is instantiated because none already exists. The second time, when we create the <code>mysql<\/code> object, no new object is instantiated but instead, the reference to the object that was instantiated earlier, i.e. the <code>mongo<\/code> object, is returned.<\/p>\n\n\n\n<p>class Database {<br>\n  constructor(data) {<br>\n    if (Database.exists) {<br>\n      return Database.instance;<br>\n    }<br>\n    this._data = data;<br>\n    Database.instance = this;<br>\n    Database.exists = true;<br>\n    return this;<br>\n  }<\/p>\n\n\n\n<p>getData() {<br>\n    return this._data;<br>\n  }<\/p>\n\n\n\n<p>setData(data) {<br>\n    this._data = data;<br>\n  }<br>\n}<\/p>\n\n\n\n<p>\/\/ usage<br>\nconst mongo = new Database(&#8216;mongo&#8217;);<br>\nconsole.log(mongo.getData()); \/\/ mongo<\/p>\n\n\n\n<p>const mysql = new Database(&#8216;mysql&#8217;);<br> console.log(mysql.getData()); \/\/ mongo<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"6054\">Adapter Pattern<\/h1>\n\n\n\n<p>This\n is a structural pattern where the interface of one class is translated \ninto another. This pattern lets classes work together that could not \notherwise because of incompatible interfaces.<\/p>\n\n\n\n<p>This\n pattern is often used to create wrappers for new refactored APIs so \nthat other existing old APIs can still work with them. This is usually \ndone when new implementations or code refactoring (done for reasons like\n performance gains) result in a different public API, while the other \nparts of the system are still using the old API and need to be adapted \nto work together.<\/p>\n\n\n\n<p>In this example, we have an old API, i.e. <code>OldCalculator<\/code> class, and a new API, i.e. <code>NewCalculator<\/code> class. The <code>OldCalculator<\/code> class provides an <code>operation<\/code>method for both addition and subtraction, while the <code>NewCalculator<\/code> provides separate methods for addition and subtraction. The Adapter class <code>CalcAdapter<\/code>wraps the <code>NewCalculator<\/code> to add the <code>operation<\/code> method to the public-facing API while using its own addition and subtraction implementation under the hood.<\/p>\n\n\n\n<p>\/\/ old interface<br>\nclass OldCalculator {<br>\n  constructor() {<br>\n    this.operations = function(term1, term2, operation) {<br>\n      switch (operation) {<br>\n        case &#8216;add&#8217;:<br>\n          return term1 + term2;<br>\n        case &#8216;sub&#8217;:<br>\n          return term1 &#8211; term2;<br>\n        default:<br>\n          return NaN;<br>\n      }<br>\n    };<br>\n  }<br>\n}<\/p>\n\n\n\n<p>\/\/ new interface<br>\nclass NewCalculator {<br>\n  constructor() {<br>\n    this.add = function(term1, term2) {<br>\n      return term1 + term2;<br>\n    };<br>\n    this.sub = function(term1, term2) {<br>\n      return term1 &#8211; term2;<br>\n    };<br>\n  }<br>\n}<\/p>\n\n\n\n<p>\/\/ Adapter Class<br>\nclass CalcAdapter {<br>\n  constructor() {<br>\n    const newCalc = new NewCalculator();<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>this.operations = function(term1, term2, operation) {\n  switch (operation) {\n    case 'add':\n      \/\/ using the new implementation under the hood\n      return newCalc.add(term1, term2);\n    case 'sub':\n      return newCalc.sub(term1, term2);\n    default:\n      return NaN;\n  }\n};<\/code><\/pre>\n\n\n\n<p>}<br>\n}<\/p>\n\n\n\n<p>\/\/ usage<br>\nconst oldCalc = new OldCalculator();<br>\nconsole.log(oldCalc.operations(10, 5, &#8216;add&#8217;)); \/\/ 15<\/p>\n\n\n\n<p>const newCalc = new NewCalculator();<br>\nconsole.log(newCalc.add(10, 5)); \/\/ 15<\/p>\n\n\n\n<p>const adaptedCalc = new CalcAdapter();<br> console.log(adaptedCalc.operations(10, 5, &#8216;add&#8217;)); \/\/ 15;<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"fde5\">Composite Pattern<\/h1>\n\n\n\n<p>This  is a structural design pattern that composes objects into tree-like  structures to represent whole-part hierarchies. In this pattern, each  node in the tree-like structure can be either an individual object or a  composed collection of objects. Regardless, each node is treated  uniformly.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"373\" height=\"251\" src=\"https:\/\/cebucodesolutions.com\/blog\/wp-content\/uploads\/2020\/04\/1-yAkeYCKDaRQtMRAV2Kx5sA.png\" alt=\"\" class=\"wp-image-59\" srcset=\"https:\/\/cebucodesolutions.com\/blog\/wp-content\/uploads\/2020\/04\/1-yAkeYCKDaRQtMRAV2Kx5sA.png 373w, https:\/\/cebucodesolutions.com\/blog\/wp-content\/uploads\/2020\/04\/1-yAkeYCKDaRQtMRAV2Kx5sA-300x202.png 300w\" sizes=\"auto, (max-width: 373px) 85vw, 373px\" \/><\/figure>\n\n\n\n<p>It\n is a bit complex to visualize this pattern. The easiest way to think \nabout this is with the example of a multi-level menu. Each node can be a\n distinct option, or it can be a menu itself, which has multiple options\n as its child. A node component with children is a composite component, \nwhile a node component without any child is a leaf component.<\/p>\n\n\n\n<p>In this example, we create a base class of <code>Component<\/code>  that implements the common functionalities needed and abstracts the  other methods needed. The base class also has a static method that  utilises recursion to traverse a composite tree structure made with its  subclasses. Then we create two subclasses extending the base class \u2014 <code>Leaf<\/code> that does not have any children and <code>Composite<\/code>  that can have children\u2014and hence have methods handling adding,  searching, and removing child functionalities. The two subclasses are  used to create a composite structure\u2014a tree, in this case.<\/p>\n\n\n\n<p>class Component {<br>\n  constructor(name) {<br>\n    this._name = name;<br>\n  }<\/p>\n\n\n\n<p>getNodeName() {<br>\n    return this._name;<br>\n  }<\/p>\n\n\n\n<p>\/\/ abstract methods that need to be overridden<br>\n  getType() {}<\/p>\n\n\n\n<p>addChild(component) {}<\/p>\n\n\n\n<p>removeChildByName(componentName) {}<\/p>\n\n\n\n<p>removeChildByIndex(index) {}<\/p>\n\n\n\n<p>getChildByName(componentName) {}<\/p>\n\n\n\n<p>getChildByIndex(index) {}<\/p>\n\n\n\n<p>noOfChildren() {}<\/p>\n\n\n\n<p>static logTreeStructure(root) {<br>\n    let treeStructure = &#8221;;<br>\n    function traverse(node, indent = 0) {<br>\n      treeStructure += <code>${'--'.repeat(indent)}${node.getNodeName()}\\n<\/code>;<br>\n      indent++;<br>\n      for (let i = 0, length = node.noOfChildren(); i &lt; length; i++) {<br>\n        traverse(node.getChildByIndex(i), indent);<br>\n      }<br>\n    }<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>traverse(root);\nreturn treeStructure;<\/code><\/pre>\n\n\n\n<p>}<br>\n}<\/p>\n\n\n\n<p>class Leaf extends Component {<br>\n  constructor(name) {<br>\n    super(name);<br>\n    this._type = &#8216;Leaf Node&#8217;;<br>\n  }<\/p>\n\n\n\n<p>getType() {<br>\n    return this._type;<br>\n  }<\/p>\n\n\n\n<p>noOfChildren() {<br>\n    return 0;<br>\n  }<br>\n}<\/p>\n\n\n\n<p>class Composite extends Component {<br>\n  constructor(name) {<br>\n    super(name);<br>\n    this._type = &#8216;Composite Node&#8217;;<br>\n    this._children = [];<br>\n  }<\/p>\n\n\n\n<p>getType() {<br>\n    return this._type;<br>\n  }<\/p>\n\n\n\n<p>addChild(component) {<br>\n    this._children = [\u2026this._children, component];<br>\n  }<\/p>\n\n\n\n<p>removeChildByName(componentName) {<br>\n    this._children = [\u2026this._children].filter(component =&gt; component.getNodeName() !== componentName);<br>\n  }<\/p>\n\n\n\n<p>removeChildByIndex(index) {<br>\n    this._children = [\u2026this._children.slice(0, index), \u2026this._children.slice(index + 1)];<br>\n  }<\/p>\n\n\n\n<p>getChildByName(componentName) {<br>\n    return this._children.find(component =&gt; component.name === componentName);<br>\n  }<\/p>\n\n\n\n<p>getChildByIndex(index) {<br>\n    return this._children[index];<br>\n  }<\/p>\n\n\n\n<p>noOfChildren() {<br>\n    return this._children.length;<br>\n  }<br>\n}<\/p>\n\n\n\n<p>\/\/ usage<br>\nconst tree = new Composite(&#8216;root&#8217;);<br>\ntree.addChild(new Leaf(&#8216;left&#8217;));<br>\nconst right = new Composite(&#8216;right&#8217;);<br>\ntree.addChild(right);<br>\nright.addChild(new Leaf(&#8216;right-left&#8217;));<br>\nconst rightMid = new Composite(&#8216;right-middle&#8217;);<br>\nright.addChild(rightMid);<br>\nright.addChild(new Leaf(&#8216;right-right&#8217;));<br>\nrightMid.addChild(new Leaf(&#8216;left-end&#8217;));<br>\nrightMid.addChild(new Leaf(&#8216;right-end&#8217;));<\/p>\n\n\n\n<p>\/\/ log<br> console.log(Component.logTreeStructure(tree));<br> \/*<br> root<br> &#8211;left<br> &#8211;right<br> &#8212;-right-left<br> &#8212;-right-middle<br> &#8212;&#8212;left-end<br> &#8212;&#8212;right-end<br> &#8212;-right-right<br> *\/<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"db35\">Decorator Pattern<\/h1>\n\n\n\n<p>This\n is also a structural design pattern that focuses on the ability to add \nbehaviour or functionalities to existing classes dynamically. It is \nanother viable alternative to sub-classing.<\/p>\n\n\n\n<p>The\n decorator type behaviour is very easy to implement in JavaScript \nbecause JavaScript allows us to add methods and properties to object \ndynamically. The simplest approach would be to just add a property to an\n object, but it will not be efficiently reusable.<\/p>\n\n\n\n<p>In fact, there is a proposal to add decorators to the JavaScript language. Take a look at <a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/medium.com\/google-developers\/exploring-es7-decorators-76ecb65fb841\"><strong>Addy Osmani\u2019s post<\/strong><\/a> about decorators in JavaScript.<\/p>\n\n\n\n<p>If you want to read about the <a href=\"https:\/\/tc39.es\/proposal-decorators\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>proposal itself<\/strong><\/a>, feel free.<\/p>\n\n\n\n<p>In this example, we create a <code>Book<\/code> class. We further create two decorator functions that accept a book object and return a \u201cdecorated\u201d <code>book<\/code> object \u2014 <code>giftWrap<\/code> that adds one new attribute and one new function and <code>hardbindBook<\/code> that adds one new attribute and edits the value of one existing attribute.<\/p>\n\n\n\n<p>class Book {<br>\n  constructor(title, author, price) {<br>\n    this._title = title;<br>\n    this._author = author;<br>\n    this.price = price;<br>\n  }<\/p>\n\n\n\n<p>getDetails() {<br>\n    return <code>${this._title} by ${this._author}<\/code>;<br>\n  }<br>\n}<\/p>\n\n\n\n<p>\/\/ decorator 1<br>\nfunction giftWrap(book) {<br>\n  book.isGiftWrapped = true;<br>\n  book.unwrap = function() {<br>\n    return <code>Unwrapped ${book.getDetails()}<\/code>;<br>\n  };<\/p>\n\n\n\n<p>return book;<br>\n}<\/p>\n\n\n\n<p>\/\/ decorator 2<br>\nfunction hardbindBook(book) {<br>\n  book.isHardbound = true;<br>\n  book.price += 5;<br>\n  return book;<br>\n}<\/p>\n\n\n\n<p>\/\/ usage<br>\nconst alchemist = giftWrap(new Book(&#8216;The Alchemist&#8217;, &#8216;Paulo Coelho&#8217;, 10));<\/p>\n\n\n\n<p>console.log(alchemist.isGiftWrapped); \/\/ true<br>\nconsole.log(alchemist.unwrap()); \/\/ &#8216;Unwrapped The Alchemist by Paulo Coelho&#8217;<\/p>\n\n\n\n<p>const inferno = hardbindBook(new Book(&#8216;Inferno&#8217;, &#8216;Dan Brown&#8217;, 15));<\/p>\n\n\n\n<p>console.log(inferno.isHardbound); \/\/ true<br> console.log(inferno.price); \/\/ 20<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"28e9\">Fa\u00e7ade Pattern<\/h1>\n\n\n\n<p>This\n is a structural design pattern that is widely used in the JavaScript \nlibraries. It is used to provide a unified and simpler, public-facing \ninterface for ease of use that shields away from the complexities of its\n consisting subsystems or subclasses.<\/p>\n\n\n\n<p>The use of this pattern is very common in libraries like jQuery.<\/p>\n\n\n\n<p>In this example, we create a public facing API with the class <code>ComplaintRegistry<\/code>. It exposes only one method to be used by the client, i.e. <code>registerComplaint<\/code>. It internally handles instantiating required objects of either <code>ProductComplaint<\/code> or <code>ServiceComplaint<\/code>  based on the type argument. It also handles all the other complex  functionalities like generating a unique ID, storing the complaint in  memory, etc. But, all these complexities are hidden away using the  fa\u00e7ade pattern.<\/p>\n\n\n\n<p>let currentId = 0;<\/p>\n\n\n\n<p>class ComplaintRegistry {<br>\n  registerComplaint(customer, type, details) {<br>\n    const id = ComplaintRegistry._uniqueIdGenerator();<br>\n    let registry;<br>\n    if (type === &#8216;service&#8217;) {<br>\n      registry = new ServiceComplaints();<br>\n    } else {<br>\n      registry = new ProductComplaints();<br>\n    }<br>\n    return registry.addComplaint({ id, customer, details });<br>\n  }<\/p>\n\n\n\n<p>static _uniqueIdGenerator() {<br>\n    return ++currentId;<br>\n  }<br>\n}<\/p>\n\n\n\n<p>class Complaints {<br>\n  constructor() {<br>\n    this.complaints = [];<br>\n  }<\/p>\n\n\n\n<p>addComplaint(complaint) {<br>\n    this.complaints.push(complaint);<br>\n    return this.replyMessage(complaint);<br>\n  }<\/p>\n\n\n\n<p>getComplaint(id) {<br>\n    return this.complaints.find(complaint =&gt; complaint.id === id);<br>\n  }<\/p>\n\n\n\n<p>replyMessage(complaint) {}<br>\n}<\/p>\n\n\n\n<p>class ProductComplaints extends Complaints {<br>\n  constructor() {<br>\n    super();<br>\n    if (ProductComplaints.exists) {<br>\n      return ProductComplaints.instance;<br>\n    }<br>\n    ProductComplaints.instance = this;<br>\n    ProductComplaints.exists = true;<br>\n    return this;<br>\n  }<\/p>\n\n\n\n<p>replyMessage({ id, customer, details }) {<br>\n    return <code>Complaint No. ${id} reported by ${customer} regarding ${details} have been filed with the Products Complaint Department. Replacement\/Repairment of the product as per terms and conditions will be carried out soon.<\/code>;<br>\n  }<br>\n}<\/p>\n\n\n\n<p>class ServiceComplaints extends Complaints {<br>\n  constructor() {<br>\n    super();<br>\n    if (ServiceComplaints.exists) {<br>\n      return ServiceComplaints.instance;<br>\n    }<br>\n    ServiceComplaints.instance = this;<br>\n    ServiceComplaints.exists = true;<br>\n    return this;<br>\n  }<\/p>\n\n\n\n<p>replyMessage({ id, customer, details }) {<br>\n    return <code>Complaint No. ${id} reported by ${customer} regarding ${details} have been filed with the Service Complaint Department. The issue will be resolved or the purchase will be refunded as per terms and conditions.<\/code>;<br>\n  }<br>\n}<\/p>\n\n\n\n<p>\/\/ usage<br>\nconst registry = new ComplaintRegistry();<\/p>\n\n\n\n<p>const reportService = registry.registerComplaint(&#8216;Martha&#8217;, &#8216;service&#8217;, &#8216;availability&#8217;);<br>\n\/\/ &#8216;Complaint No. 1 reported by Martha regarding availability have been filed with the Service Complaint Department. The issue will be resolved or the purchase will be refunded as per terms and conditions.&#8217;<\/p>\n\n\n\n<p>const reportProduct = registry.registerComplaint(&#8216;Jane&#8217;, &#8216;product&#8217;, &#8216;faded color&#8217;);<br> \/\/ &#8216;Complaint No. 2 reported by Jane regarding faded color have been filed with the Products Complaint Department. Replacement\/Repairment of the product as per terms and conditions will be carried out soon.&#8217;<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"f163\">Flyweight Pattern<\/h1>\n\n\n\n<p>This\n is a structural design pattern focused on efficient data sharing \nthrough fine-grained objects. It is used for efficiency and memory \nconservation purposes.<\/p>\n\n\n\n<p>This\n pattern can be used for any kind of caching purposes. In fact, modern \nbrowsers use a variant of a flyweight pattern to prevent loading the \nsame images twice.<\/p>\n\n\n\n<p>In this example, we create a fine-grained flyweight class <code>Icecream<\/code> for sharing data regarding ice-cream flavours and a factory class <code>IcecreamFactory<\/code>  to create those flyweight objects. For memory conservation, the objects  are recycled if the same object is instantiated twice. This is a simple  example of flyweight implementation.<\/p>\n\n\n\n<p>\/\/ flyweight class<br>\nclass Icecream {<br>\n  constructor(flavour, price) {<br>\n    this.flavour = flavour;<br>\n    this.price = price;<br>\n  }<br>\n}<\/p>\n\n\n\n<p>\/\/ factory for flyweight objects<br>\nclass IcecreamFactory {<br>\n  constructor() {<br>\n    this._icecreams = [];<br>\n  }<\/p>\n\n\n\n<p>createIcecream(flavour, price) {<br>\n    let icecream = this.getIcecream(flavour);<br>\n    if (icecream) {<br>\n      return icecream;<br>\n    } else {<br>\n      const newIcecream = new Icecream(flavour, price);<br>\n      this._icecreams.push(newIcecream);<br>\n      return newIcecream;<br>\n    }<br>\n  }<\/p>\n\n\n\n<p>getIcecream(flavour) {<br>\n    return this._icecreams.find(icecream =&gt; icecream.flavour === flavour);<br>\n  }<br>\n}<\/p>\n\n\n\n<p>\/\/ usage<br>\nconst factory = new IcecreamFactory();<\/p>\n\n\n\n<p>const chocoVanilla = factory.createIcecream(&#8216;chocolate and vanilla&#8217;, 15);<br>\nconst vanillaChoco = factory.createIcecream(&#8216;chocolate and vanilla&#8217;, 15);<\/p>\n\n\n\n<p>\/\/ reference to the same object<br> console.log(chocoVanilla === vanillaChoco); \/\/ true<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"e1d3\">Proxy Pattern<\/h1>\n\n\n\n<p>This\n is a structural design pattern that behaves exactly as its name \nsuggests. It acts as a surrogate or placeholder for another object to \ncontrol access to it.<\/p>\n\n\n\n<p>It\n is usually used in situations in which a target object is under \nconstraints and may not be able to handle all its responsibilities \nefficiently. A proxy, in this case, usually provides the same interface \nto the client and adds a level of indirection to support controlled \naccess to the target object to avoid undue pressure on it.<\/p>\n\n\n\n<p>The\n proxy pattern can be very useful when working with network \nrequest-heavy applications to avoid unnecessary or redundant network \nrequests.<\/p>\n\n\n\n<p>In this example, we will use two new ES6 features, <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Proxy\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Proxy<\/strong><\/a> and <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Reflect\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Reflect<\/strong><\/a>.\n A Proxy object is used to define custom behaviour for fundamental \noperations of a JavaScript object (remember, function and arrays are \nalso object in JavaScript). It is a constructor method that can be used \nto create a <code>Proxy<\/code> object. It accepts a <code>target<\/code> object that is to be proxied and a <code>handler<\/code> object that will define the necessary customisation. The handler object allows for defining some trap functions like <code>get<\/code>, <code>set<\/code>, <code>has<\/code>, <code>apply<\/code>, etc. that are used to add custom behaviour attached to their usage. <code>Reflect<\/code>,\n on the other hand, is a built-in object that provides similar methods \nthat are supported by the handler object of Proxy as static methods on \nitself. It is not a constructor; its static methods are used for \nintercept-able JavaScript operations.<\/p>\n\n\n\n<p>Now, we create a function that can be thought of as a network request. We named it as <code>networkFetch<\/code>.\n It accepts a URL and responds accordingly. We want to implement a proxy\n where we only get the response from the network if it is not available \nin our cache. Otherwise, we just return a response from the cache.<\/p>\n\n\n\n<p>The <code>cache<\/code> global variable will store our cached responses. We create a proxy named <code>proxiedNetworkFetch<\/code> with our original <code>networkFetch<\/code> as the <code>target<\/code>and use apply method in our <code>handler<\/code> object to proxy the function invocation. The apply method gets passed on the <code>target<\/code> object itself. This value as <code>thisArg<\/code> and the arguments are passed to it in an array-like structure <code>args<\/code>.<\/p>\n\n\n\n<p>We  check if the passed url argument is in the cache. If it exists in the  cache, we return the response from there, never invoking the original  target function. If it does not, then we use the <code>Reflect.apply<\/code> method to invoke the <code>target<\/code>function with <code>thisArg<\/code> (although it\u2019s not of any significance in our case here) and the arguments it passed.<\/p>\n\n\n\n<p>\/\/ Target<br>\nfunction networkFetch(url) {<br>\n  return <code>${url} - Response from network<\/code>;<br>\n}<\/p>\n\n\n\n<p>\/\/ Proxy<br>\n\/\/ ES6 Proxy API = new Proxy(target, handler);<br>\nconst cache = [];<br>\nconst proxiedNetworkFetch = new Proxy(networkFetch, {<br>\n  apply(target, thisArg, args) {<br>\n    const urlParam = args[0];<br>\n    if (cache.includes(urlParam)) {<br>\n      return <code>${urlParam} - Response from cache<\/code>;<br>\n    } else {<br>\n      cache.push(urlParam);<br>\n      return Reflect.apply(target, thisArg, args);<br>\n    }<br>\n  },<br>\n});<\/p>\n\n\n\n<p>\/\/ usage<br> console.log(proxiedNetworkFetch(&#8216;dogPic.jpg&#8217;)); \/\/ &#8216;dogPic.jpg &#8211; Response from network&#8217;<br> console.log(proxiedNetworkFetch(&#8216;dogPic.jpg&#8217;)); \/\/ &#8216;dogPic.jpg &#8211; Response from cache&#8217;<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"8faf\">Chain of Responsibility Pattern<\/h1>\n\n\n\n<p>This\n is a behavioural design pattern that provides a chain of loosely \ncoupled objects. Each of these objects can choose to act on or handle \nthe request of the client.<\/p>\n\n\n\n<p>A\n good example of the chain of responsibility pattern is the event \nbubbling in DOM in which an event propagates through a series of nested \nDOM elements, one of which may have an \u201cevent listener\u201d attached to \nlisten to and act on the event.<\/p>\n\n\n\n<p>In this example, we create a class <code>CumulativeSum<\/code>, which can be instantiated with an optional <code>initialValue<\/code>. It has a method <code>add<\/code> that adds the passed value to the <code>sum<\/code> attribute of the object and returns the <code>object<\/code> itself to allow chaining of <code>add<\/code> method calls.<\/p>\n\n\n\n<p>This is a common pattern that can be seen in <a rel=\"noreferrer noopener\" href=\"https:\/\/jquery.com\/\" target=\"_blank\"><strong>jQuery<\/strong><\/a> as well, where almost any method call on a jQuery object returns a jQuery object so that method calls can be chained together.<\/p>\n\n\n\n<p>class CumulativeSum {<br>\n  constructor(intialValue = 0) {<br>\n    this.sum = intialValue;<br>\n  }<\/p>\n\n\n\n<p>add(value) {<br>\n    this.sum += value;<br>\n    return this;<br>\n  }<br>\n}<\/p>\n\n\n\n<p>\/\/ usage<br>\nconst sum1 = new CumulativeSum();<br>\nconsole.log(sum1.add(10).add(2).add(50).sum); \/\/ 62<\/p>\n\n\n\n<p>const sum2 = new CumulativeSum(10);<br> console.log(sum2.add(10).add(20).add(5).sum); \/\/ 45<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"6b07\">Command Pattern<\/h1>\n\n\n\n<p>This\n is a behavioural design pattern that aims to encapsulate actions or \noperations as objects. This pattern allows loose coupling of systems and\n classes by separating the objects that request an operation or invoke a\n method from the ones that execute or process the actual implementation.<\/p>\n\n\n\n<p>The clipboard interaction API somewhat resembles the command pattern. If you are a <a href=\"https:\/\/redux.js.org\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Redux<\/strong><\/a>\n user, you have already come across the command pattern. The actions \nthat allow the awesome time-travel debugging feature are nothing but \nencapsulated operations that can be tracked to redo or undo operations. \nHence, time-travelling made possible.<\/p>\n\n\n\n<p>In this example, we have a class called <code>SpecialMath<\/code> that has multiple methods and a <code>Command<\/code> class that encapsulates commands that are to be executed on its subject, i.e. an object of the <code>SpecialMath<\/code> class. The <code>Command<\/code>  class also keeps track of all the commands executed, which can be used  to extend its functionality to include undo and redo type operations.<\/p>\n\n\n\n<p>class SpecialMath {<br>\n  constructor(num) {<br>\n    this._num = num;<br>\n  }<\/p>\n\n\n\n<p>square() {<br>\n    return this._num ** 2;<br>\n  }<\/p>\n\n\n\n<p>cube() {<br>\n    return this._num ** 3;<br>\n  }<\/p>\n\n\n\n<p>squareRoot() {<br>\n    return Math.sqrt(this._num);<br>\n  }<br>\n}<\/p>\n\n\n\n<p>class Command {<br>\n  constructor(subject) {<br>\n    this._subject = subject;<br>\n    this.commandsExecuted = [];<br>\n  }<br>\n  execute(command) {<br>\n    this.commandsExecuted.push(command);<br>\n    return this._subject[command]();<br>\n  }<br>\n}<\/p>\n\n\n\n<p>\/\/ usage<br>\nconst x = new Command(new SpecialMath(5));<br>\nx.execute(&#8216;square&#8217;);<br>\nx.execute(&#8216;cube&#8217;);<\/p>\n\n\n\n<p>console.log(x.commandsExecuted); \/\/ [&#8216;square&#8217;, &#8216;cube&#8217;]<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"6de9\">Iterator Pattern<\/h1>\n\n\n\n<p>It\n is a behavioural design pattern that provides a way to access the \nelements of an aggregate object sequentially without exposing its \nunderlying representation.<\/p>\n\n\n\n<p>Iterators have a special kind of behaviour where we step through an ordered set of values one at a time by calling <code>next()<\/code>\n until we reach the end. The introduction of Iterator and Generators in \nES6 made the implementation of the iterator pattern extremely \nstraightforward.<\/p>\n\n\n\n<p>We have two examples below. First, one <code>IteratorClass<\/code> uses iterator spec, while the other one <code>iteratorUsingGenerator<\/code> uses generator functions.<\/p>\n\n\n\n<p>The <code>Symbol.iterator<\/code> ( <code>Symbol<\/code>\u2014a\n new kind of primitive data type) is used to specify the default \niterator for an object. It must be defined for a collection to be able \nto use the <code>for...of<\/code> looping construct. In the first example, we define the constructor to store some collection of data and then define <code>Symbol.iterator<\/code>, which returns an object with <code>next<\/code> method for iteration.<\/p>\n\n\n\n<p>For the second case, we define a generator function passing it an array of data and returning its elements iteratively using <code>next<\/code> and <code>yield<\/code>.  A generator function is a special type of function that works as a  factory for iterators and can explicitly maintain its own internal state  and yield values iteratively. It can pause and resume its own execution  cycle.<\/p>\n\n\n\n<p>\/\/ using Iterator<br>\nclass IteratorClass {<br>\n  constructor(data) {<br>\n    this.index = 0;<br>\n    this.data = data;<br>\n  }<\/p>\n\n\n\n<p>[Symbol.iterator]() {<br>\n    return {<br>\n      next: () =&gt; {<br>\n        if (this.index &lt; this.data.length) {<br>\n          return { value: this.data[this.index++], done: false };<br>\n        } else {<br>\n          this.index = 0; \/\/ to reset iteration status<br>\n          return { done: true };<br>\n        }<br>\n      },<br>\n    };<br>\n  }<br>\n}<\/p>\n\n\n\n<p>\/\/ using Generator<br>\nfunction* iteratorUsingGenerator(collection) {<br>\n  var nextIndex = 0;<\/p>\n\n\n\n<p>while (nextIndex &lt; collection.length) {<br>\n    yield collection[nextIndex++];<br>\n  }<br>\n}<\/p>\n\n\n\n<p>\/\/ usage<br>\nconst gen = iteratorUsingGenerator([&#8216;Hi&#8217;, &#8216;Hello&#8217;, &#8216;Bye&#8217;]);<\/p>\n\n\n\n<p>console.log(gen.next().value); \/\/ &#8216;Hi&#8217;<br> console.log(gen.next().value); \/\/ &#8216;Hello&#8217;<br> console.log(gen.next().value); \/\/ &#8216;Bye&#8217;<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"efb2\">Mediator Pattern<\/h1>\n\n\n\n<p>It\n is a behavioural design pattern that encapsulates how a set of objects \ninteract with each other. It provides the central authority over a group\n of objects by promoting loose coupling, keeping objects from referring \nto each other explicitly.<\/p>\n\n\n\n<p>In this example, we have <code>TrafficTower<\/code> as Mediator that controls the way <code>Airplane<\/code> objects interact with each other. All the <code>Airplane<\/code> objects register themselves with a <code>TrafficTower<\/code> object, and it is the mediator class object that handles how an <code>Airplane<\/code> object receives coordinates data of all the other <code>Airplane<\/code> objects.<\/p>\n\n\n\n<p>class TrafficTower {<br>\n  constructor() {<br>\n    this._airplanes = [];<br>\n  }<\/p>\n\n\n\n<p>register(airplane) {<br>\n    this._airplanes.push(airplane);<br>\n    airplane.register(this);<br>\n  }<\/p>\n\n\n\n<p>requestCoordinates(airplane) {<br>\n    return this._airplanes.filter(plane =&gt; airplane !== plane).map(plane =&gt; plane.coordinates);<br>\n  }<br>\n}<\/p>\n\n\n\n<p>class Airplane {<br>\n  constructor(coordinates) {<br>\n    this.coordinates = coordinates;<br>\n    this.trafficTower = null;<br>\n  }<\/p>\n\n\n\n<p>register(trafficTower) {<br>\n    this.trafficTower = trafficTower;<br>\n  }<\/p>\n\n\n\n<p>requestCoordinates() {<br>\n    if (this.trafficTower) return this.trafficTower.requestCoordinates(this);<br>\n    return null;<br>\n  }<br>\n}<\/p>\n\n\n\n<p>\/\/ usage<br>\nconst tower = new TrafficTower();<\/p>\n\n\n\n<p>const airplanes = [new Airplane(10), new Airplane(20), new Airplane(30)];<br>\nairplanes.forEach(airplane =&gt; {<br>\n  tower.register(airplane);<br>\n});<\/p>\n\n\n\n<p>console.log(airplanes.map(airplane =&gt; airplane.requestCoordinates())) <br> \/\/ [[20, 30], [10, 30], [10, 20]]<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"1dbc\">Observer Pattern<\/h1>\n\n\n\n<p>It\n is a crucial behavioural design pattern that defines one-to-many \ndependencies between objects so that when one object (publisher) changes\n its state, all the other dependent objects (subscribers) are notified \nand updated automatically. This is also called PubSub \n(publisher\/subscribers) or event dispatcher\/listeners pattern. The \npublisher is sometimes called the subject, and the subscribers are \nsometimes called observers.<\/p>\n\n\n\n<p>Chances are, you\u2019re already somewhat familiar with this pattern if you have used <code>addEventListener<\/code> or jQuery\u2019s .<code>on<\/code> to write even-handling code. It has its influences in Reactive Programming (think <a href=\"https:\/\/rxjs-dev.firebaseapp.com\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>RxJS<\/strong><\/a>) as well.<\/p>\n\n\n\n<p>In the example, we create a simple <code>Subject<\/code> class that has methods to add and remove objects of <code>Observer<\/code> class from subscriber collection. Also, a <code>fire<\/code>method to propagate any changes in the <code>Subject<\/code> class object to the subscribed Observers. The <code>Observer<\/code>\n class, on the other hand, has its internal state and a method to update\n its internal state based on the change propagated from the <code>Subject<\/code> it has subscribed to.<\/p>\n\n\n\nclass Subject {\n  constructor() {\n    this._observers = [];\n  }\n\n  subscribe(observer) {\n    this._observers.push(observer);\n  }\n\n  unsubscribe(observer) {\n    this._observers = this._observers.filter(obs =&gt; observer !== obs);\n  }\n\n  fire(change) {\n    this._observers.forEach(observer =&gt; {\n      observer.update(change);\n    });\n  }\n}\n\nclass Observer {\n  constructor(state) {\n    this.state = state;\n    this.initialState = state;\n  }\n\n  update(change) {\n    let state = this.state;\n    switch (change) {\n      case &#8216;INC&#8217;:\n        this.state = ++state;\n        break;\n      case &#8216;DEC&#8217;:\n        this.state = &#8211;state;\n        break;\n      default:\n        this.state = this.initialState;\n    }\n  }\n}\n\n\/\/ usage\nconst sub = new Subject();\n\nconst obs1 = new Observer(1);\nconst obs2 = new Observer(19);\n\nsub.subscribe(obs1);\nsub.subscribe(obs2);\n\nsub.fire(&#8216;INC&#8217;);\n\nconsole.log(obs1.state); \/\/ 2\nconsole.log(obs2.state); \/\/ 20\n\n\n\n<h1 class=\"wp-block-heading\" id=\"56a9\">State Pattern<\/h1>\n\n\n\n<p>It\n is a behavioural design pattern that allows an object to alter its \nbehaviour based on changes to its internal state. The object returned by\n a state pattern class seems to change its class. It provides \nstate-specific logic to a limited set of objects in which each object \ntype represents a particular state.<\/p>\n\n\n\n<p>We will take a simple example of a traffic light to understand this pattern. The <code>TrafficLight<\/code> class changes the object it returns based on its internal state, which is an object of <code>Red<\/code>, <code>Yellow<\/code>, or <code>Green<\/code> class.<\/p>\n\n\n\n<p>class TrafficLight {<br>\n  constructor() {<br>\n    this.states = [new GreenLight(), new RedLight(), new YellowLight()];<br>\n    this.current = this.states[0];<br>\n  }<\/p>\n\n\n\n<p>change() {<br>\n    const totalStates = this.states.length;<br>\n    let currentIndex = this.states.findIndex(light =&gt; light === this.current);<br>\n    if (currentIndex + 1 &lt; totalStates) this.current = this.states[currentIndex + 1];<br>\n    else this.current = this.states[0];<br>\n  }<\/p>\n\n\n\n<p>sign() {<br>\n    return this.current.sign();<br>\n  }<br>\n}<\/p>\n\n\n\n<p>class Light {<br>\n  constructor(light) {<br>\n    this.light = light;<br>\n  }<br>\n}<\/p>\n\n\n\n<p>class RedLight extends Light {<br>\n  constructor() {<br>\n    super(&#8216;red&#8217;);<br>\n  }<\/p>\n\n\n\n<p>sign() {<br>\n    return &#8216;STOP&#8217;;<br>\n  }<br>\n}<\/p>\n\n\n\n<p>class YellowLight extends Light {<br>\n  constructor() {<br>\n    super(&#8216;yellow&#8217;);<br>\n  }<\/p>\n\n\n\n<p>sign() {<br>\n    return &#8216;STEADY&#8217;;<br>\n  }<br>\n}<\/p>\n\n\n\n<p>class GreenLight extends Light {<br>\n    constructor() {<br>\n        super(&#8216;green&#8217;);<br>\n    }<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sign() {\n    return 'GO';\n}<\/code><\/pre>\n\n\n\n<p>}<\/p>\n\n\n\n<p>\/\/ usage<br>\nconst trafficLight = new TrafficLight();<\/p>\n\n\n\n<p>console.log(trafficLight.sign()); \/\/ &#8216;GO&#8217;<br>\ntrafficLight.change();<\/p>\n\n\n\n<p>console.log(trafficLight.sign()); \/\/ &#8216;STOP&#8217;<br>\ntrafficLight.change();<\/p>\n\n\n\n<p>console.log(trafficLight.sign()); \/\/ &#8216;STEADY&#8217;<br>\ntrafficLight.change();<\/p>\n\n\n\n<p>console.log(trafficLight.sign()); \/\/ &#8216;GO&#8217;<br>\ntrafficLight.change();<\/p>\n\n\n\n<p>console.log(trafficLight.sign()); \/\/ &#8216;STOP&#8217;<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"87e7\">Strategy Pattern<\/h1>\n\n\n\n<p>It\n is a behavioural design pattern that allows encapsulation of \nalternative algorithms for a particular task. It defines a family of \nalgorithms and encapsulates them in such a way that they are \ninterchangeable at runtime without client interference or knowledge.<\/p>\n\n\n\n<p>In the example below, we create a class <code>Commute<\/code> for encapsulating all the possible strategies for commuting to work. Then, we define three strategies namely <code>Bus<\/code>, <code>PersonalCar<\/code>, and <code>Taxi<\/code>. Using this pattern we can swap the implementation to use for the <code>travel<\/code> method of the <code>Commute<\/code> object at runtime.<\/p>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>\/\/ encapsulation<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>class Commute {<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>  travel(transport) {<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>    return transport.travelTime();<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>  }<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>}<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>class Vehicle {<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>  travelTime() {<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>    return this._timeTaken;<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>  }<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>}<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>\/\/ strategy 1<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>class Bus extends Vehicle {<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>  constructor() {<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>    super();<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>    this._timeTaken = 10;<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>  }<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>}<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>\/\/ strategy 2<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>class Taxi extends Vehicle {<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>  constructor() {<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>    super();<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>    this._timeTaken = 5;<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>  }<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>}<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>\/\/ strategy 3<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>class PersonalCar extends Vehicle {<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>  constructor() {<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>    super();<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>    this._timeTaken = 3;<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>  }<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>}<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>\/\/ usage<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>const commute = new Commute();<\/td><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><\/tr><\/tbody><\/table>\n\n\n\n<table class=\"wp-block-table\"><tbody><tr><td>console.log(commute.travel(new Taxi())); \/\/ 5<\/td><\/tr><\/tbody><\/table>\n\n\n\n<p>console.log(commute.travel(new Bus())); \/\/ 10<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"c927\">Template Pattern<\/h1>\n\n\n\n<p>This\n is a behavioural design pattern based on defining the skeleton of the \nalgorithm or implementation of an operation, but deferring some steps to\n subclasses. It lets subclasses redefine certain steps of an algorithm \nwithout changing the algorithm\u2019s outward structure.<\/p>\n\n\n\n<p>In this example, we have a Template class <code>Employee<\/code> that implements <code>work<\/code>method  partially. It is for the subclasses to implement responsibilities  method to make it work as a whole. We then create two subclasses <code>Developer<\/code> and <code>Tester<\/code> that extend the template class and implement the required method to fill the implementation gap.<\/p>\n\n\n\n<p>class Employee {<br>\n  constructor(name, salary) {<br>\n    this._name = name;<br>\n    this._salary = salary;<br>\n  }<\/p>\n\n\n\n<p>work() {<br>\n    return <code>${this._name} handles ${this.responsibilities() \/* gap to be filled by subclass *\/}<\/code>;<br>\n  }<\/p>\n\n\n\n<p>getPaid() {<br>\n    return <code>${this._name} got paid ${this._salary}<\/code>;<br>\n  }<br>\n}<\/p>\n\n\n\n<p>class Developer extends Employee {<br>\n  constructor(name, salary) {<br>\n    super(name, salary);<br>\n  }<\/p>\n\n\n\n<p>\/\/ details handled by subclass<br>\n  responsibilities() {<br>\n    return &#8216;application development&#8217;;<br>\n  }<br>\n}<\/p>\n\n\n\n<p>class Tester extends Employee {<br>\n  constructor(name, salary) {<br>\n    super(name, salary);<br>\n  }<\/p>\n\n\n\n<p>\/\/ details handled by subclass<br>\n  responsibilities() {<br>\n    return &#8216;testing&#8217;;<br>\n  }<br>\n}<\/p>\n\n\n\n<p>\/\/ usage<br>\nconst dev = new Developer(&#8216;Nathan&#8217;, 100000);<br>\nconsole.log(dev.getPaid()); \/\/ &#8216;Nathan got paid 100000&#8217;<br>\nconsole.log(dev.work()); \/\/ &#8216;Nathan handles application development&#8217;<\/p>\n\n\n\n<p>const tester = new Tester(&#8216;Brian&#8217;, 90000);<br> console.log(tester.getPaid()); \/\/ &#8216;Brian got paid 90000&#8217;<br> console.log(tester.work()); \/\/ &#8216;Brian handles testing&#8217;<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"bfde\">Conclusion<\/h1>\n\n\n\n<p>Design\n patterns are crucial to software engineering and can be very helpful in\n solving common problems. But this is a very vast subject, and it is \nsimply not possible to include everything about them in a short piece. \nTherefore, I made the choice to shortly and concisely talk only about \nthe ones I think can be really handy in writing modern JavaScript. To \ndive deeper, I suggest you take a look at these books:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><a href=\"https:\/\/en.wikipedia.org\/wiki\/Design_Patterns\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Design Patterns: Elements Of Reusable Object-Oriented Software<\/strong><\/a>by <em>Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides (Gang of Four)<\/em><\/li><li><a href=\"https:\/\/addyosmani.com\/resources\/essentialjsdesignpatterns\/book\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Learn JavaScript Design Patterns<\/strong> <\/a>by <em>Addy Osmani<\/em><\/li><li><a href=\"http:\/\/www.amazon.com\/JavaScript-Patterns-Stoyan-Stefanov\/dp\/0596806752\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>JavaScript Patterns<\/strong><\/a> by <em>Stoyan Stefanov<\/em><\/li><\/ol>\n","protected":false},"excerpt":{"rendered":"<p>The ultimate guide to the most useful design patterns UPDATE NOTE: Updated the Proxy Pattern example to use ES6 Proxy and Reflect. Replaced images of source code snippets with GitHub gists. In this article, we are going to talk about design patterns that can be and should be used to write better, maintainable JavaScript code. &hellip; <a href=\"https:\/\/cebucodesolutions.com\/blog\/2020\/04\/22\/javascript-design-patterns\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;JavaScript Design Patterns&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-54","post","type-post","status-publish","format-standard","hentry","category-updates"],"_links":{"self":[{"href":"https:\/\/cebucodesolutions.com\/blog\/wp-json\/wp\/v2\/posts\/54","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/cebucodesolutions.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cebucodesolutions.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/cebucodesolutions.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/cebucodesolutions.com\/blog\/wp-json\/wp\/v2\/comments?post=54"}],"version-history":[{"count":1,"href":"https:\/\/cebucodesolutions.com\/blog\/wp-json\/wp\/v2\/posts\/54\/revisions"}],"predecessor-version":[{"id":60,"href":"https:\/\/cebucodesolutions.com\/blog\/wp-json\/wp\/v2\/posts\/54\/revisions\/60"}],"wp:attachment":[{"href":"https:\/\/cebucodesolutions.com\/blog\/wp-json\/wp\/v2\/media?parent=54"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cebucodesolutions.com\/blog\/wp-json\/wp\/v2\/categories?post=54"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cebucodesolutions.com\/blog\/wp-json\/wp\/v2\/tags?post=54"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}