<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ singleton - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ singleton - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 24 Jun 2026 17:36:20 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/singleton/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Singleton Design Pattern – How it Works in JavaScript with Example Code ]]>
                </title>
                <description>
                    <![CDATA[ At one point or another, you might need to use global state inside your React apps. This lets you have your data in one place and make sure the required components can access it. To help you do this, you'll often use some sort of state management lib... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/singleton-design-pattern-with-javascript/</link>
                <guid isPermaLink="false">66bb5558bf1e2b114113ed98</guid>
                
                    <category>
                        <![CDATA[ design patterns ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ singleton ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Keyur Paralkar ]]>
                </dc:creator>
                <pubDate>Mon, 18 Jul 2022 19:26:56 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/sven-mieke-fteR0e2BzKo-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>At one point or another, you might need to use global state inside your React apps. This lets you have your data in one place and make sure the required components can access it.</p>
<p>To help you do this, you'll often use some sort of state management library like Redux, React Context, or Recoil.</p>
<p>But in this article we are going to learn about global state management with the help of design patterns.</p>
<p>We will look at what design patterns are, and we'll focus on the singleton design pattern in particular. Finally we will look at an example of the singleton design pattern along with its advantages and disadvantages.</p>
<p>So without any further ado, let's get started.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-design-pattern">What is a design pattern</a>?</p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-singleton-design-pattern">What is the singleton design pattern</a>?</p>
</li>
<li><p><a class="post-section-overview" href="#heading-pros-and-cons-of-the-singleton-design-pattern">Pros and cons of the singleton design pattern</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before going through this article, I would highly recommend being familiar with the content in the following articles:</p>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/javascript-classes-how-they-work-with-use-case/">What are classes in JavaScript</a>?</p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction#accessing_the_dom">How to access DOM elements</a></p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze">How object freeze works</a></p>
</li>
</ul>
<h2 id="heading-what-is-a-design-pattern">What is a Design Pattern?</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/ezgif.com-gif-maker--9-.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Design patterns provide conceptual solutions to common problems</em></p>
<p>A design pattern is a set of generalised instructions that provide a solution to commonly occurring problems in software design.</p>
<p>You can think about design patterns as a website that consists of multiple design templates you can use to build a site based on your specific needs.</p>
<p>So, now the question is – why is it important to know design patterns? Well, using design patterns has several benefits, such as:</p>
<ul>
<li><p>These patterns are proven – that is, these instructions are tried and tested, and they reflect the experience and insights of many developers.</p>
</li>
<li><p>They're patterns that you can re-use easily.</p>
</li>
<li><p>They are highly expressive.</p>
</li>
</ul>
<p>Note that design patterns provide just a conceptual solution to a recurring problem in an optimised way. It does not provide a piece of code that you can use in your project.</p>
<p>So now that we know what design patterns are, let's dive into our very first design pattern.</p>
<h2 id="heading-what-is-the-singleton-design-pattern">What is the Singleton Design Pattern?</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/singleton-def-gif.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Singleton design pattern exposes a single instance that can be used by multiple components</em></p>
<p>Singleton is a design pattern that tells us that we can create only one instance of a class and that instance can be accessed globally.</p>
<p>This is one of the basic types of design pattern. It makes sure that the class acts as a single source of entry for all the consumer components that want to access this state. In other words, it provides a common entry point for using global state.</p>
<p>So a singleton class should be one which:</p>
<ul>
<li><p>Ensures that it creates only one instance of the class</p>
</li>
<li><p>Provides a global access point to the state.</p>
</li>
<li><p>Makes sure that the instance is only created the first time.</p>
</li>
</ul>
<h3 id="heading-example-of-the-singleton-design-pattern">Example of the Singleton Design Pattern</h3>
<p>To understand this concept in a better way, let's look at an example. This example is a simple React application that demonstrates how the global state value is used across the components, how it is being changed, and how the same value gets updated in all the components. Let's get started.</p>
<p>Before we start with the actual implementation, let's have a look at the folder structure:</p>
<pre><code class="lang-yaml"><span class="hljs-string">.</span>
<span class="hljs-string">├──</span> <span class="hljs-string">index.html</span>
<span class="hljs-string">├──</span> <span class="hljs-string">package.json</span>
<span class="hljs-string">└──</span> <span class="hljs-string">src</span>
    <span class="hljs-string">├──</span> <span class="hljs-string">componentA.js</span>
    <span class="hljs-string">├──</span> <span class="hljs-string">componentB.js</span>
    <span class="hljs-string">├──</span> <span class="hljs-string">globalStyles.js</span>
    <span class="hljs-string">├──</span> <span class="hljs-string">index.js</span>
    <span class="hljs-string">├──</span> <span class="hljs-string">styles.css</span>
    <span class="hljs-string">└──</span> <span class="hljs-string">utilities.js</span>
</code></pre>
<p>Here are the details of each file:</p>
<ul>
<li><p><code>componentA.js</code> is a consumer component that uses the singleton class to access the global state object and manipulate it.</p>
</li>
<li><p><code>componentB.js</code> is similar to above component, as it has to access the global state object and can manipulate it.</p>
</li>
<li><p><code>globalStyles.js</code> is a module that consists of the singleton class and exports the instance of this class.</p>
</li>
<li><p><code>index.js</code> manages global JS operations, that is JavaScript changes that are required for other DOM elements.</p>
</li>
<li><p><code>styles.css</code> manages the styling of the application. Consists of basic CSS.</p>
</li>
<li><p><code>utilities.js</code> is a module that exports some utility functions.</p>
</li>
<li><p><code>index.html</code> consists of HTML code for the components that are required in the project.</p>
</li>
<li><p><code>package.json</code> is a boilerplate configuration emitted by the <code>npm init</code> command.</p>
</li>
</ul>
<p>Now that we know what each file does, we can start off by implementing them one by one.</p>
<p>But before we dive into this example, we need to understand the code flow. The aim of our example is to build a JavaScript application that demonstrates how the global style <code>color</code> is consumed by each of the components and how each component changes it.</p>
<p>Each component consists of a <code>color-picker</code>. When you change the global style <code>color</code> property via the color picker present inside each component, it automatically appears in other components and in the global state.</p>
<p>First, let's create a file: <code>index.html</code>. Then paste the below code into this file:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Parcel Sandbox<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"./src/styles.css"</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"global-state"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Global State<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h4</span>&gt;</span>Color<span class="hljs-tag">&lt;/<span class="hljs-name">h4</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"selected-color"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"contents"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"component-a"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>Component A<span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Pick color<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"selected-color"</span>&gt;</span>black<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"color"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"color-picker-a"</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"component-b"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>Component B<span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Pick color<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"selected-color"</span>&gt;</span>black<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"color"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"color-picker-b"</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"src/index.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"src/componentA.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"src/componentB.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Here at the top, we load our CSS via <code>&lt;link rel="stylesheet" href="./src/styles.css" /&gt;</code>.</p>
<p>Then we have divided our application in two parts via two classes:</p>
<ul>
<li><p><code>.global-state</code>: This will represent the HTML code for showcasing the current global state of the application.</p>
</li>
<li><p><code>.contents</code>: This will represent the HTML code that represents the two components.</p>
</li>
</ul>
<p>Each of the components (<code>component-a</code> and <code>component-b</code>) has a color picker input element.</p>
<p>Both of these components have a <code>span</code> with class <code>selected-color</code> element that will help display the current value of global state variable <code>color</code>.</p>
<p>As you can see on a change of the color picker inside <code>componentA</code>, the following values are also changing:</p>
<ul>
<li><p>Value inside the <code>.selected-color</code> span element inside the <code>componentB</code> and Global state.</p>
</li>
<li><p>Value of the color picker of <code>componentA</code> and <code>componentB</code>.</p>
</li>
</ul>
<p>We will see later how all these values are changing. But for now it is important for us to understand that if we change the global state value from one component, then the singleton classes make sure that the instance value is updated and all the components that are consuming this instance get the same value since they are referring to the same instance.</p>
<p>Next, we create a file named <code>globalStyles.js</code>. Copy-paste the below code in it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> instance;
<span class="hljs-keyword">let</span> globalState = {
  <span class="hljs-attr">color</span>: <span class="hljs-string">""</span>
};

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StateUtility</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-keyword">if</span> (instance) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"New instance cannot be created!!"</span>);
    }

    instance = <span class="hljs-built_in">this</span>;
  }

  getPropertyByName(propertyName) {
    <span class="hljs-keyword">return</span> globalState[propertyName];
  }

  setPropertyValue(propertyName, propertyValue) {
    globalState[propertyName] = propertyValue;
  }
}

<span class="hljs-keyword">let</span> stateUtilityInstance = <span class="hljs-built_in">Object</span>.freeze(<span class="hljs-keyword">new</span> StateUtility());

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> stateUtilityInstance;
</code></pre>
<p>The above piece of code is a module that has a singleton class <code>StateUtility</code> and default exports the instance of the same class.</p>
<p>Let's dive deeper into the class <code>StateUtility</code> to understand how it resolves to become a singleton class:</p>
<ul>
<li><p>It consists of <code>constructor</code> and two class methods called <code>getPropertyByName</code> and <code>setPropertyValue</code>. Both of these class method are pretty self explanatory: one gets the property's value and the other sets its value.</p>
</li>
<li><p>Next, we have the <code>constructor</code> function. It is a function that gets invoked whenever we create a new of object of this class.</p>
</li>
<li><p>But here is a catch: for a class to be a singleton we need to make sure that it creates only one instance, and that's all.</p>
</li>
<li><p>To make sure that this happens, we simply create a global variable called <code>instance</code>. We define it at the top of the module. This variable acts as a checker. We add a condition in the <code>constructor</code> function such that if <code>instance</code> variable has any value (that is, the object of the <code>StateUtility</code> class) then throw an error or else assign <code>instance</code> to the current class instance (the <code>this</code> object).</p>
</li>
<li><p>In this example, we implemented the class <code>StateUtility</code> so that it can expose and alter the <code>globalState</code> variable.</p>
</li>
<li><p>We make sure that we don't expose the <code>globalState</code>. We expose them using the class methods of <code>StateUtility</code>. In this way, we protect the global state from being altered directly.</p>
</li>
<li><p>Finally, we create the instance of the class as follows: <code>let stateUtilityInstance = Object.freeze(new StateUtility());</code>.</p>
</li>
<li><p>We have used <code>Object.freeze</code> so that no other class/component/module is able to modify the exposed <code>stateUtilityInstance</code>.</p>
</li>
</ul>
<p>Then let's create a file called <code>componentA.js</code> inside the <code>src</code> folder. Copy-paste the below code in this file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {
    setAllSelectedColor
} <span class="hljs-keyword">from</span> <span class="hljs-string">"./utilities"</span>;
<span class="hljs-keyword">import</span> globalStyle <span class="hljs-keyword">from</span> <span class="hljs-string">"./globalStyles"</span>;

<span class="hljs-comment">// Get respective dom elements</span>
<span class="hljs-keyword">const</span> selectedColor = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">"#selected-color"</span>);
<span class="hljs-keyword">const</span> colorPickerA = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"color-picker-a"</span>);
<span class="hljs-keyword">const</span> colorPickerB = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"color-picker-b"</span>);

<span class="hljs-comment">// Event handler whenever a change event occurs</span>
colorPickerA.onchange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    <span class="hljs-comment">// set the color property of the global state with current color picker's value;</span>
    globalStyle.setPropertyValue(<span class="hljs-string">"color"</span>, event.target.value);
    <span class="hljs-keyword">const</span> color = globalStyle.getPropertyByName(<span class="hljs-string">"color"</span>);

    <span class="hljs-comment">// A function thats sets the value of all the #selection-color dom elements;</span>
    setValueOfSimilarElements(selectedColor, color);

    <span class="hljs-comment">// make sure to set the component B's color picker value is set to color picker A;</span>
    <span class="hljs-comment">// this is done to make sure that both of the color picker have same value on change;</span>
    colorPickerB.value = color;
};
</code></pre>
<p>Here is the breakdown of the above piece of code:</p>
<ul>
<li><p>The aim of this code is to make sure that we attach the <code>onChange</code> handler for the color picker that is present inside the <code>component-a</code>. In this case, componentA's color picker is identified by id: <code>#color-picker-a</code>.</p>
</li>
<li><p>We need to make sure that this handler:</p>
<ol>
<li><p>Sets the value for the property color of the globalState.</p>
</li>
<li><p>Fetches the same property again.</p>
</li>
<li><p>Applies the same value to different areas of the DOM.</p>
</li>
<li><p>Also makes sure that we set the other color picker's value to the global state.</p>
</li>
</ol>
</li>
</ul>
<p>Now, let's take a look at all these steps one-by-one:</p>
<ul>
<li><p>First, let's fetch all the required DOM elements.</p>
</li>
<li><p>What we are planning here is to update all the color pickers and span elements with id <code>#selected-color</code> with the value of the current globalState property color whenever the on change event occurs.</p>
</li>
<li><p>In case of <code>componentA</code>, once we change the color via the color picker we need to update the same value in 2 span elements (<code>#selected-color</code>) – that is, one span element of <code>componentB</code> and one span element present in the <code>.global-state</code> div container.</p>
</li>
<li><p>We do this because we want to keep all the components in sync and demosntrate that the value of the global state remains the same across all the components.</p>
</li>
<li><p>We then go ahead and update the <code>color</code> property of the global state using the <code>StateUtility</code>'s class method <code>setPropertyValue</code>. We pass on to it <code>event.target.value</code> as this contains the current value present inside the <code>#color-picker-a</code> color picker input.</p>
</li>
<li><p>Once the value is set, we fetch the same property again by using <code>getPropertyByName</code>. We do this to demonstrate that the property <code>color</code> of the global state has been updated and is ready to be used.</p>
</li>
<li><p>Then, we use the <code>setValueOfSimilarElements</code> utility function to update all the elements that are having same class/id name with some value. In this case we update all the <code>#selected-color</code> elements with value <code>color</code>.</p>
</li>
<li><p>Finally, we update the the value of the opposite color picker, that is componentB's color picker <code>#color-picker-b</code>.</p>
</li>
</ul>
<p>We do the same thing for <code>componentB</code>. We create a file called <code>componentB.js</code> and update it with the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {
    setValueOfSimilarElements
} <span class="hljs-keyword">from</span> <span class="hljs-string">"./utilities"</span>;
<span class="hljs-keyword">import</span> globalStyle <span class="hljs-keyword">from</span> <span class="hljs-string">"./globalStyles"</span>;

<span class="hljs-comment">// Get respective dom elements</span>
<span class="hljs-keyword">const</span> selectedColor = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">"#selected-color"</span>);
<span class="hljs-keyword">const</span> colorPickerA = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"color-picker-a"</span>);
<span class="hljs-keyword">const</span> colorPickerB = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"color-picker-b"</span>);

<span class="hljs-comment">/**
 * Event handler whenever a change event occurs
 */</span>
colorPickerB.onchange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    <span class="hljs-comment">// set the color property of the global state with current color picker's value;</span>
    globalStyle.setPropertyValue(<span class="hljs-string">"color"</span>, event.target.value);

    <span class="hljs-keyword">const</span> color = globalStyle.getPropertyByName(<span class="hljs-string">"color"</span>);

    <span class="hljs-comment">// A function thats sets the value of all the #selection-color dom elements</span>
    setValueOfSimilarElements(selectedColor, color);

    <span class="hljs-comment">// make sure to set the component A's color picker value is set to color picker B;</span>
    <span class="hljs-comment">// this is done to make sure that both of the color picker have same value on change;</span>
    colorPickerA.value = color;
};
</code></pre>
<p>We do the same thing as of what we did inside the <code>componentA</code> file, but in this case we update the value of the color picker present inside <code>componentA</code> (that is, we update the value of element <code>#color-picker-a</code>).</p>
<p>Here is how our application will look like:</p>
<p><a target="_blank" href="https://zqbo69.csb.app/">Here is the link to the code</a>:</p>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codesandbox.io/embed/zqbo69?view=editor+%2B+preview" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodeSandbox embed" allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-pros-and-cons-of-the-singleton-design-pattern">Pros and Cons of the Singleton Design Pattern</h2>
<p>Here are some of the pros of using the Singleton design pattern:</p>
<ul>
<li><p>It makes sure that only a single instance of the class is created.</p>
</li>
<li><p>We get a single access point to the instance that can be accessed globally.</p>
</li>
</ul>
<p>Here are some cons of the Singleton design pattern:</p>
<ul>
<li><p>It violates the single responsibility principle. That is, it tries to solve two problems at the same time. It tries to solve the following problems: <em>Ensure that a class will have only one instance</em>, and <em>assigning a global access point to the singleton class instance.</em></p>
</li>
<li><p>It is difficult to write unit test cases for singleton classes. This is because the order of execution can change the value present in the global state, so the order of execution is important.</p>
</li>
<li><p>While writing unit tests, there is a risk of another component or a module might be changing the global state value/instance. In such scenarios, it becomes difficult to debug the error.</p>
</li>
</ul>
<h2 id="heading-summary">Summary</h2>
<p>The singleton design pattern can be useful in creating a global state that can be accessed by any component.</p>
<p>So to talk about singleton pattern in brief:</p>
<ul>
<li><p>It is a pattern that restricts the class to create only one instance.</p>
</li>
<li><p>Singleton pattern can be considered the basics of global state management libraries such Redux or React Context.</p>
</li>
<li><p>They can be accessed globally and acts as a single access point for accessing the global state.</p>
</li>
</ul>
<p>That's all.</p>
<p>Thank you for reading!</p>
<p>Follow me on <a target="_blank" href="https://twitter.com/keurplkar">Twitter</a>, <a target="_blank" href="https://github.com/keyurparalkar">GitHub</a>, and <a target="_blank" href="https://www.linkedin.com/in/keyur-paralkar-494415107/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The 3 Types of Design Patterns All Developers Should Know (with code examples of each) ]]>
                </title>
                <description>
                    <![CDATA[ By Sameeha Rahman What is a Design Pattern? Design patterns are design level solutions for recurring problems that we software engineers come across often. It’s not code - I repeat, ❌CODE. It is like a description on how to tackle these problems and ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-basic-design-patterns-all-developers-need-to-know/</link>
                <guid isPermaLink="false">66d460cfe39d8b5612bc0df1</guid>
                
                    <category>
                        <![CDATA[ command ]]>
                    </category>
                
                    <category>
                        <![CDATA[ decorator ]]>
                    </category>
                
                    <category>
                        <![CDATA[ design patterns ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ singleton ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 24 Jul 2019 06:52:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/07/design-patterns-everywhere.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Sameeha Rahman</p>
<h1 id="heading-what-is-a-design-pattern">What is a Design Pattern?</h1>
<p>Design patterns are design level solutions for recurring problems that we software engineers come across often. It’s not code - I repeat, ❌<strong>CODE</strong>. It is like a description on how to tackle these problems and design a solution. </p>
<p>Using these patterns is considered good practice, as the design of the solution is quite tried and tested, resulting in higher readability of the final code. Design patterns are quite often created for and used by OOP Languages, like Java, in which most of the examples from here on will be written.</p>
<h2 id="heading-types-of-design-patterns">Types of design patterns</h2>
<p>There are about 26 Patterns currently discovered (I hardly think I will do them all…).</p>
<p>These 26 can be classified into 3 types:</p>
<ol>
<li><p>Creational: These patterns are designed for class instantiation. They can be either class-creation patterns or object-creational patterns.</p>
</li>
<li><p>Structural: These patterns are designed with regard to a class's structure and composition. The main goal of most of these patterns is to increase the functionality of the class(es) involved, without changing much of its composition.</p>
</li>
<li><p>Behavioral: These patterns are designed depending on how one class communicates with others.</p>
</li>
</ol>
<p>In this post, we will go through one basic design pattern for each classified type.</p>
<h2 id="heading-type-1-creational-the-singleton-design-pattern">Type 1: Creational - The Singleton Design Pattern</h2>
<p>The Singleton Design Pattern is a Creational pattern, whose objective is to create only one instance of a class and to provide only one global access point to that object. One commonly used example of such a class in Java is Calendar, where you cannot make an instance of that class. It also uses its own <code>getInstance()</code>method to get the object to be used.</p>
<p>A class using the singleton design pattern will include,</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/singleton-class-diagram.png" alt="Image" width="600" height="400" loading="lazy">
<em>Singleton Class Diagram</em></p>
<ol>
<li>A private static variable, holding the only instance of the class.</li>
<li>A private constructor, so it cannot be instantiated anywhere else.</li>
<li>A public static method, to return the single instance of the class.</li>
</ol>
<p>There are many different implementations of singleton design. Today, I’ll be going through the implementations of;</p>
<ol>
<li><p>Eager Instantiation</p>
</li>
<li><p>Lazy Instantiation</p>
</li>
<li><p>Thread-safe Instantiation</p>
</li>
</ol>
<h3 id="heading-eager-beaver">Eager Beaver</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EagerSingleton</span> </span>{
    <span class="hljs-comment">// create an instance of the class.</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> EagerSingleton instance = <span class="hljs-keyword">new</span> EagerSingleton();

    <span class="hljs-comment">// private constructor, so it cannot be instantiated outside this class.</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">EagerSingleton</span><span class="hljs-params">()</span> </span>{  }

    <span class="hljs-comment">// get the only instance of the object created.</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> EagerSingleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> instance;
    }
}
</code></pre>
<p>This type of instantiation happens during class loading, as the instantiation of the variable instance happens outside any method. This poses a hefty drawback if this class is not being used at all by the client application. The contingency plan, if this class is not being used, is the Lazy Instantiation.</p>
<h3 id="heading-lazy-days">Lazy Days</h3>
<p>There isn’t much difference from the above implementation. The main differences are that the static variable is initially declared null, and is only instantiated within the <code>getInstance()</code> method if - and only if - the instance variable remains null at the time of the check. </p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LazySingleton</span> </span>{
    <span class="hljs-comment">// initialize the instance as null.</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> LazySingleton instance = <span class="hljs-keyword">null</span>;

    <span class="hljs-comment">// private constructor, so it cannot be instantiated outside this class.</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">LazySingleton</span><span class="hljs-params">()</span> </span>{  }

    <span class="hljs-comment">// check if the instance is null, and if so, create the object.</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> LazySingleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">if</span> (instance == <span class="hljs-keyword">null</span>) {
            instance = <span class="hljs-keyword">new</span> LazySingleton();
        }
        <span class="hljs-keyword">return</span> instance;
    }
}
</code></pre>
<p>This fixes one problem, but another one still exists. What if two different clients access the Singleton class at the same time, right to the millisecond? Well, they will check if the instance is null at the same time, and will find it true, and so will create two instances of the class for each request by the two clients. To fix this, Thread Safe instantiation is to be implemented.</p>
<h3 id="heading-thread-safety-is-key">(Thread) Safety is Key</h3>
<p>In Java, the keyword synchronized is used on methods or objects to implement thread safety, so that only one thread will access a particular resource at one time. The class instantiation is put within a synchronized block so that the method can only be accessed by one client at a given time.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThreadSafeSingleton</span> </span>{
    <span class="hljs-comment">// initialize the instance as null.</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> ThreadSafeSingleton instance = <span class="hljs-keyword">null</span>;

    <span class="hljs-comment">// private constructor, so it cannot be instantiated outside this class.</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">ThreadSafeSingleton</span><span class="hljs-params">()</span> </span>{  }

    <span class="hljs-comment">// check if the instance is null, within a synchronized block. If so, create the object</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ThreadSafeSingleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">synchronized</span> (ThreadSafeSingleton.class) {
            <span class="hljs-keyword">if</span> (instance == <span class="hljs-keyword">null</span>) {
                instance = <span class="hljs-keyword">new</span> ThreadSafeSingleton();
            }
        }
        <span class="hljs-keyword">return</span> instance;
    }
}
</code></pre>
<p>The overhead for the synchronized method is high, and reduces the performance of the whole operation. </p>
<p>For example, if the instance variable has already been instantiated, then each time any client accesses the <code>getInstance()</code> method, the <code>synchronized</code> method is run and the performance drops. This just happens in order to check if the <code>instance</code> variables’ value is null. If it finds that it is, it leaves the method. </p>
<p>To reduce this overhead, double locking is used. The check is used before the <code>synchronized</code> method as well, and if the value is null alone, does the <code>synchronized</code> method run.</p>
<pre><code class="lang-java"><span class="hljs-comment">// double locking is used to reduce the overhead of the synchronized method</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ThreadSafeSingleton <span class="hljs-title">getInstanceDoubleLocking</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">if</span> (instance == <span class="hljs-keyword">null</span>) {
        <span class="hljs-keyword">synchronized</span> (ThreadSafeSingleton.class) {
            <span class="hljs-keyword">if</span> (instance == <span class="hljs-keyword">null</span>) {
                instance = <span class="hljs-keyword">new</span> ThreadSafeSingleton();
            }
        }
    }
    <span class="hljs-keyword">return</span> instance;
}
</code></pre>
<p>Now onto the next classification.</p>
<h2 id="heading-type-2-structural-the-decorator-design-pattern">Type 2: Structural - The Decorator Design Pattern</h2>
<p>I’m gonna give you a small scenario to give a better context to why and where you should use the Decorator Pattern.</p>
<p>Say you own a coffee shop, and like any newbie, you start out with just two types of plain coffee, the house blend and dark roast. In your billing system, there was one class for the different coffee blends, which inherits the beverage abstract class. People actually start to come by and have your wonderful (albeit bitter?) coffee. Then there are the coffee newbs that, God forbid, want sugar or milk. Such a travesty for coffee!! ??</p>
<p>Now you need to have those two add-ons as well, both to the menu and unfortunately on the billing system. Originally, your IT person will make a subclass for both coffees, one including sugar, the other milk. Then, since customers are always right, one says these dreaded words:</p>
<p><em>“Can I get a milk coffee, with sugar, please?”</em></p>
<h3 id="heading-pz8">???</h3>
<p>There goes your billing system laughing in your face again. Well, back to the drawing board….</p>
<p>The IT person then adds milk coffee with sugar as another subclass to each parent coffee class. The rest of the month is smooth sailing, people lining up to have your coffee, you actually making money. ??</p>
<p>But wait, there’s more!</p>
<p>The world is against you once again. A competitor opens up across the street, with not just 4 types of coffee, but more than 10 add-ons as well!</p>
<p>You buy all those and more, to sell better coffee yourself, and just then remember that you forgot to update that dratted billing system. You quite possibly cannot make the infinite number of subclasses for any and all combinations of all the add-ons, with the new coffee blends too. Not to mention, the size of the final system.</p>
<p>Time to actually invest in a proper billing system. You find new IT personnel, who actually knows what they are doing and they say,</p>
<p><em>“Why, this will be so much easier and smaller if it used the decorator pattern.”</em></p>
<h3 id="heading-what-on-earth-is-that">What on earth is that?</h3>
<p>The decorator design pattern falls into the structural category, that deals with the actual structure of a class, whether is by inheritance, composition or both. The goal of this design is to modify an objects’ functionality at runtime. This is one of the many other design patterns that utilize abstract classes and interfaces with composition to get its desired result.</p>
<p>Let’s give Math a chance (shudder?) to bring this all into perspective.</p>
<p>Take 4 coffee blends and 10 add-ons. If we stuck to the generation of subclasses for each different combination of all the add-ons for one type of coffee. That’s:</p>
<p>(10–1)² = 9² = 81 subclasses</p>
<p>We subtract 1 from the 10, as you cannot combine one add-on with another of the same type, sugar with sugar sounds stupid. And that’s for just one coffee blend. Multiply that <strong>81 by 4</strong> and you get a whopping <strong>324</strong> different subclasses! Talk about all that coding…</p>
<p>But with the decorator pattern it will require only 16 classes in this scenario. Wanna bet?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/decorator-class-diagram.png" alt="Image" width="600" height="400" loading="lazy">
<em>Decorator Design Pattern Class diagram</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/decorator-coffee-class-diagram.png" alt="Image" width="600" height="400" loading="lazy">
<em>Class diagram according to coffee shop scenario</em></p>
<p>If we map out our scenario according to the class diagram above, we get 4 classes for the 4 coffee blends, 10 for each add-on and 1 for the abstract component and 1 more for the abstract decorator. See! 16! Now hand over that $100.?? (jk, but it will not be refused if given… just saying)</p>
<p>As you can see from above, just as the concrete coffee blends are subclasses of the beverage abstract class, the AddOn abstract class also inherits its methods from it. The add-ons, that are its subclasses, in turn inherit any new methods to add functionality to the base object when needed.</p>
<p>Let’s get to coding, to see this pattern in use.</p>
<p>First to make the Abstract beverage class, that all the different coffee blends will inherit from:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Beverage</span> </span>{
    <span class="hljs-keyword">private</span> String description;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Beverage</span><span class="hljs-params">(String description)</span> </span>{
        <span class="hljs-keyword">super</span>();
        <span class="hljs-keyword">this</span>.description = description;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> description;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">double</span> <span class="hljs-title">cost</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<p>Then to add both the concrete coffee blend classes.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HouseBlend</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Beverage</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">HouseBlend</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">super</span>(“House blend”);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">cost</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-number">250</span>;
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DarkRoast</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Beverage</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DarkRoast</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">super</span>(“Dark roast”);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">cost</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-number">300</span>;
    }
}
</code></pre>
<p>The AddOn abstract class also inherits from the Beverage abstract class (more on this below).</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AddOn</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Beverage</span> </span>{
    <span class="hljs-keyword">protected</span> Beverage beverage;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">AddOn</span><span class="hljs-params">(String description, Beverage bev)</span> </span>{
        <span class="hljs-keyword">super</span>(description);
        <span class="hljs-keyword">this</span>.beverage = bev;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<p>And now the concrete implementations of this abstract class:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Sugar</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AddOn</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Sugar</span><span class="hljs-params">(Beverage bev)</span> </span>{
        <span class="hljs-keyword">super</span>(“Sugar”, bev);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> beverage.getDescription() + “ with Mocha”;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">cost</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> beverage.cost() + <span class="hljs-number">50</span>;
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Milk</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AddOn</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Milk</span><span class="hljs-params">(Beverage bev)</span> </span>{
        <span class="hljs-keyword">super</span>(“Milk”, bev);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> beverage.getDescription() + “ with Milk”;
    }

    <span class="hljs-meta">@Override</span>  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">cost</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> beverage.cost() + <span class="hljs-number">100</span>;
    }
}
</code></pre>
<p>As you can see above, we can pass any subclass of Beverage to any subclass of AddOn, and get the added cost as well as the updated description. And, since the AddOn class is essentially of type Beverage, we can pass an AddOn into another AddOn. This way, we can add any number of add-ons to a specific coffee blend.</p>
<p>Now to write some code to test this out.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CoffeeShop</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        HouseBlend houseblend = <span class="hljs-keyword">new</span> HouseBlend();
        System.out.println(houseblend.getDescription() + “: “ + houseblend.cost());

        Milk milkAddOn = <span class="hljs-keyword">new</span> Milk(houseblend);
        System.out.println(milkAddOn.getDescription() + “: “ + milkAddOn.cost());

        Sugar sugarAddOn = <span class="hljs-keyword">new</span> Sugar(milkAddOn);
        System.out.println(sugarAddOn.getDescription() + “: “ + sugarAddOn.cost());
    }
}
</code></pre>
<p>The final result is:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/decorator-final.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>P.S. this is in Sri Lankan Rupees</em></p>
<p>It works! We were able to add more than one add-on to a coffee blend and successfully update its final cost and description, without the need to make infinite subclasses for each add-on combination for all coffee blends.</p>
<p>Finally, to the last category.</p>
<h2 id="heading-type-3-behavioral-the-command-design-pattern">Type 3: Behavioral - The Command Design Pattern</h2>
<p>A behavioral design pattern focuses on how classes and objects communicate with each other. The main focus of the command pattern is to inculcate a higher degree of loose coupling between involved parties (read: classes).</p>
<p><em>Uhhhh… What’s that?</em></p>
<p>Coupling is the way that two (or more) classes that interact with each other, well, interact. The ideal scenario when these classes interact is that they do not depend heavily on each other. That’s loose coupling. So, a better definition for loose coupling would be, classes that are interconnected, making the least use of each other.</p>
<p>The need for this pattern arose when requests needed to be sent without consciously knowing what you are asking for or who the receiver is.</p>
<p>In this pattern, the invoking class is decoupled from the class that actually performs an action. The invoker class only has the callable method execute, which runs the necessary command, when the client requests it.</p>
<p>Let’s take a basic real-world example, ordering a meal at a fancy restaurant. As the flow goes, you give your order (command) to the waiter (invoker), who then hands it over to the chef(receiver), so you can get food. Might sound simple… but a bit meh to code.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/chain-of-command-be-like-pop-snoke-im-going-to-27790631.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The idea is pretty simple, but the coding goes around the nose.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/command-class-diagram.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>Command Design Pattern Class Diagram</em></p>
<p>The flow of operation on the technical side is, you make a concrete command, which implements the Command interface, asking the receiver to complete an action, and send the command to the invoker. The invoker is the person that knows when to give this command. The chef is the only one who knows what to do when given the specific command/order. So, when the execute method of the invoker is run, it, in turn, causes the command objects’ execute method to run on the receiver, thus completing necessary actions.</p>
<h3 id="heading-what-we-need-to-implement-is">What we need to implement is;</h3>
<ol>
<li>An interface Command</li>
<li>A class Order that implements Command interface</li>
<li>A class Waiter (invoker)</li>
<li>A class Chef (receiver)</li>
</ol>
<p>So, the coding goes like this:</p>
<h3 id="heading-chef-the-receiver">Chef, the receiver</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Chef</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">cookPasta</span><span class="hljs-params">()</span> </span>{
        System.out.println(“Chef is cooking Chicken Alfredo…”);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">bakeCake</span><span class="hljs-params">()</span> </span>{
        System.out.println(“Chef is baking Chocolate Fudge Cake…”);
    }
}
</code></pre>
<h3 id="heading-command-the-interface">Command, the interface</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Command</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">execute</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<h3 id="heading-order-the-concrete-command">Order, the concrete command</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Order</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Command</span> </span>{
    <span class="hljs-keyword">private</span> Chef chef;
    <span class="hljs-keyword">private</span> String food;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Order</span><span class="hljs-params">(Chef chef, String food)</span> </span>{
        <span class="hljs-keyword">this</span>.chef = chef;
        <span class="hljs-keyword">this</span>.food = food;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">execute</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.food.equals(“Pasta”)) {
            <span class="hljs-keyword">this</span>.chef.cookPasta();
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">this</span>.chef.bakeCake();
        }
    }
}
</code></pre>
<h3 id="heading-waiter-the-invoker">Waiter, the invoker</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Waiter</span> </span>{
    <span class="hljs-keyword">private</span> Order order;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Waiter</span><span class="hljs-params">(Order ord)</span> </span>{
        <span class="hljs-keyword">this</span>.order = ord;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">execute</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">this</span>.order.execute();
    }
}
</code></pre>
<h2 id="heading-you-the-client">You, the client</h2>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Client</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Chef chef = <span class="hljs-keyword">new</span> Chef();

        Order order = <span class="hljs-keyword">new</span> Order(chef, “Pasta”);
        Waiter waiter = <span class="hljs-keyword">new</span> Waiter(order);
        waiter.execute();

        order = <span class="hljs-keyword">new</span> Order(chef, “Cake”);
        waiter = <span class="hljs-keyword">new</span> Waiter(order);
        waiter.execute();
    }
}
</code></pre>
<p>As you can see above, the Client makes an Order and sets the Receiver as the Chef. The Order is sent to the Waiter, who will know when to execute the Order (i.e. when to give the chef the order to cook). When the invoker is executed, the Orders’ execute method is run on the receiver (i.e. the chef is given the command to either cook pasta ? or bake cake?).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*gwsVqEIKFmBj01M7dXsQ_A.png" alt="Image" width="600" height="400" loading="lazy">
<em>Final Client Output</em></p>
<h2 id="heading-quick-recap">Quick recap</h2>
<p>In this post we went through:</p>
<ol>
<li>What a design pattern really is,</li>
<li>The different types of design patterns and why they are different</li>
<li>One basic or common design pattern for each type</li>
</ol>
<p>I hope this was helpful.  </p>
<p>Find the code repo for the post, <a target="_blank" href="https://github.com/samsam-026/Design_Patterns">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
