<?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" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Carlos Caballero]]></title><description><![CDATA[Thoughts, stories and ideas.]]></description><link>https://www.carloscaballero.io/</link><image><url>http://www.carloscaballero.io/favicon.png</url><title>Carlos Caballero</title><link>https://www.carloscaballero.io/</link></image><generator>Ghost 2.37</generator><lastBuildDate>Sun, 26 Apr 2026 23:34:59 GMT</lastBuildDate><atom:link href="https://www.carloscaballero.io/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Understanding the Composite Design Pattern]]></title><description><![CDATA[<p>There are 23 classic design patterns described in the original book <a href="https://amzn.to/3VN3Ygd" rel="noopener ugc nofollow"><em><em>Design Patterns: Elements of Reusable Object-Oriented Software</em></em></a>. These patterns provide solutions to particular problems often repeated in software development.</p><p>In this article, I am going to describe how the <em>Composite </em>pattern works and when it should be applied.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="composite-basic-idea">Composite:</h2>]]></description><link>https://www.carloscaballero.io/understanding-the-composite-design-pattern/</link><guid isPermaLink="false">66684ad19c7a350001e7e3fd</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Carlos Caballero]]></dc:creator><pubDate>Wed, 10 Jul 2024 19:46:45 GMT</pubDate><media:content url="http://www.carloscaballero.io/content/images/2024/06/1_7dO7bkte7tXMh7RyYtL_3Q.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://www.carloscaballero.io/content/images/2024/06/1_7dO7bkte7tXMh7RyYtL_3Q.jpg" alt="Understanding the Composite Design Pattern"><p>There are 23 classic design patterns described in the original book <a href="https://amzn.to/3VN3Ygd" rel="noopener ugc nofollow"><em><em>Design Patterns: Elements of Reusable Object-Oriented Software</em></em></a>. These patterns provide solutions to particular problems often repeated in software development.</p><p>In this article, I am going to describe how the <em>Composite </em>pattern works and when it should be applied.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="composite-basic-idea">Composite: Basic Idea</h2><p>The first thing we need to look at is the definition offered by the book from the Gang of Four:</p><blockquote>“Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.”</blockquote><p>Next, we need to look at the UML class diagram of this pattern to understand each of the elements that compose it.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/1000/0*ygjEY4eQsvDVp5W5" class="kg-image" alt="Understanding the Composite Design Pattern"></figure><!--kg-card-end: image--><p>The Composite pattern typically includes the following main elements:</p><ul><li><strong>Component</strong>: Defines the interface for objects in the composition. It declares an interface for accessing and managing children of composite objects.</li><li><strong>Leaf</strong>: Represents leaf objects in the composition. A leaf has no children. It implements the operations defined in the component interface.</li><li><strong>Composite</strong>: Defines the behavior of components that have children. It stores subcomponents and provides the implementation of operations related to children, such as adding, removing, and accessing child components.</li><li><strong>Client</strong>: Manipulates the objects in the composition through the component interface.</li></ul><p>With these elements, the <em>Composite</em> pattern allows building tree-shaped object structures that can be treated uniformly, whether it is an individual object or a composition of objects.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="when-to-use-the-composite-pattern">When to Use the Composite Pattern</h2><p>The <em>Composite</em> pattern is an excellent solution when faced with a system where a hierarchical structure of objects needs to be managed uniformly. Here are some common situations where the use of the <em>Composite</em> pattern can be beneficial:</p><ol><li><strong>Hierarchical Structures</strong>: When you need to represent object hierarchies, such as menus, organizations, or scene graphs. The <em>Composite</em> pattern facilitates the creation and manipulation of these hierarchies, allowing composite objects to contain other composite objects or leaves.</li><li><strong>Uniform Treatment of Objects</strong>: If you want clients to treat individual objects and compositions of objects in the same way, the <em>Composite</em> pattern is ideal. This simplifies client code, as it does not need to differentiate between simple and composite objects.</li><li><strong>Flexibility and Scalability</strong>: By using the <em>Composite</em> pattern, you can easily add new types of components. This facilitates the extension and modification of the structure without needing to change the code that interacts with it.</li></ol><p>In summary, the <em>Composite</em> pattern is useful in situations where there is a need to handle hierarchical structures of objects uniformly, simplify interaction with these objects, and enhance the flexibility and scalability of the system.</p><p>Let’s now look at examples of applying this pattern.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="composite-pattern-examples">Composite Pattern: Examples</h3><p>Next, we will illustrate the composite pattern with two examples:</p><ol><li><strong>Basic Structure of the Composite Pattern</strong>: In this example, we will translate the theoretical UML diagram into TypeScript code to identify each of the classes involved in the pattern.</li><li><strong>Recipe Book</strong>: We will have a set of ingredients that make up a recipe, but within a recipe, we can also have another recipe that must be made prior to our delicious dish.</li></ol><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="example-1-basic-structure-of-the-composite-pattern">Example 1: Basic Structure of the Composite Pattern</h2><p>As always, the starting point is the UML class diagram. This UML class diagram is the same as we explained at the beginning of the post, and to streamline the post, we will not explain it again as such. However, we will begin to see its implementation step by step.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/1000/0*ygjEY4eQsvDVp5W5" class="kg-image" alt="Understanding the Composite Design Pattern"></figure><!--kg-card-end: image--><p>Let’s start with the <code>Component</code> interface. This interface defines the contract that any component in the system must follow. In this case, it only has one method, <code>operation</code>, which is implemented by both leaf nodes and composite nodes.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">export interface Component {
    operation(): void;
}
</code></pre>
<!--kg-card-end: markdown--><p>The next class is <code>Leaf,</code> this class implements the <code>Component</code> interface. The <code>Leaf</code> class represents the final objects in the composition, which have no children. The <code>operation</code> method in the <code>Leaf</code> class simply performs the leaf-specific operation.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { Component } from &quot;./component&quot;;

export class Leaf implements Component {
    operation(): void {
        console.log(&quot;Leaf operation.&quot;);
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>The next class is <code>Composite</code>. This class also implements the <code>Component</code> interface. It can have children and defines operations related to its children. The <code>Composite</code> class has methods for adding and removing children, and its operation method iterates over all its children and calls their operation method.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { Component } from &quot;./component&quot;;

export class Composite implements Component {
    private children: Component[] = [];

    // Add a child to the list of children
    addChild(child: Component): void {
        this.children.push(child);
    }

    // Remove a child from the list of children
    removeChild(child: Component): void {
        const index = this.children.indexOf(child);
        if (index !== -1) {
            this.children.splice(index, 1);
        }
    }

    // Implement the operation defined in the Component interface
    operation(): void {
        console.log(&quot;Composite operation.&quot;);
        this.children.forEach(child =&gt; child.operation());
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>The <code>Composite</code> class manages a list of children who are also <code>Component</code> objects. This allows for a tree structure where each node in the tree is either a <code>Leaf</code> or a <code>Composite</code>. Now, let’s see how to use this pattern from the <code>Client</code> class.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { Component } from &quot;./component&quot;;
import { Composite } from &quot;./composite&quot;;
import { Leaf } from &quot;./leaf&quot;;

const leaf1: Component = new Leaf();
const leaf2: Component = new Leaf();
const leaf3: Component = new Leaf();
const composite1: Component = new Composite();
const composite2: Component = new Composite();

// Build the tree structure
(composite1 as Composite).addChild(leaf1);
(composite1 as Composite).addChild(leaf2);
(composite2 as Composite).addChild(leaf3);
(composite2 as Composite).addChild(composite1);

// Call the operation on the root composite
composite2.operation();
</code></pre>
<!--kg-card-end: markdown--><p>In the client code, we instantiate leaf and composite objects and build a tree structure. We add child components to composite objects, creating a hierarchy. Finally, we call the <code>operation</code> method on the root composite, which propagates the call to its children and so on, performing operations recursively.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="example-2-recipe-book-without-the-composite-pattern">Example 2: Recipe Book without the Composite Pattern</h2><p>Imagine we want to create a system to manage cooking recipes, where each recipe can consist of ingredients and other recipes. Without applying the <em>Composite</em> pattern, we would have a rigid and error-prone implementation. Below is the implementation of a recipe system without using the <em>Composite</em> pattern.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/1000/0*AycXtc4Y4c7tRJs3" class="kg-image" alt="Understanding the Composite Design Pattern"></figure><!--kg-card-end: image--><p>If we look at the UML class diagram, we first encounter the <code>Ingredient</code> class, which consists of two attributes: the <code>name</code> of the ingredient and the <code>amount</code>. The <code>showDetails</code> method is a simple <code>toString</code> method to display the information.</p><p>On the other hand, we see the <code>Recipe</code> class, which has attributes for the <code>name</code> of the recipe, a collection of <code>ingredients</code>, which are related through a composition relationship. Additionally, we have a set of recipes needed to make this recipe. Here is where we see a recursive relationship in the recipes. Moreover, the methods we need right now are quite simple: we have methods to add ingredients (<code>addIngredient</code>) and to add recipes to this entity (<code>addRecipe</code>), and a method to display the recipe details called <code>showDetails</code>.</p><p>Let’s look at the implementation of this initial solution that <strong>does NOT</strong> use the <em>Composite</em> pattern.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">export class Ingredient {
    name: string;
    amount: string;

    constructor(name: string, amount: string) {
        this.name = name;
        this.amount = amount;
    }

    showDetails(): string {
        return `Ingredient: ${this.name}, Amount: ${this.amount}`;
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>The first point is to look at the <code>Ingredient</code> class, which is a simple class where we only have the two attributes mentioned earlier: <code>name</code> and <code>amount</code>, which are received through the constructor. On the other hand, the <code>showDetails</code> method displays the information of the ingredient.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { Ingredient } from './ingredient';

export class Recipe {
    name: string;
    ingredients: Ingredient[] = [];
    recipes: Recipe[] = [];

    constructor(name: string) {
        this.name = name;
    }

    addIngredient(ingredient: Ingredient): void {
        this.ingredients.push(ingredient);
    }

    addRecipe(recipe: Recipe): void {
        this.recipes.push(recipe);
    }

    showDetails(): string {
        let details = `Recipe: ${this.name}\n`;

        this.ingredients.forEach(ingredient =&gt; {
            details += `  ${ingredient.showDetails()}\n`;
        });

        this.recipes.forEach(recipe =&gt; {
            details += `  ${recipe.showDetails()}`;
        });

        return details;
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>The next element in this solution is the <code>Recipe</code> class where we have the private attributes <code>name</code> and a list of <code>ingredients</code>, which are obvious for a recipe. Additionally, we have a recursive relationship through an attribute <code>recipes</code>, which is a collection of recipes. The constructor is quite simple as it only receives the name of the recipe, and then we have two methods that allow adding ingredients ( <code>addIngredient</code>) and recipes (<code>addRecipes</code>).</p><p>The class ends with the <code>showDetails</code> method, where we encounter two <code>for</code> loops to display the information of the ingredients and the recipes contained in this recipe.</p><p>However, at this point, we can detect serious problems that may not seem important at first, but as the project grows, they will cause significant issues in the software:</p><ol><li><strong>Method Redundancy</strong>: The <code>Recipe</code> class has two separate methods for adding components to its class, namely the <code>addIngredient</code> and <code>addRecipe</code> methods. These methods introduce redundancy and complicate the code because the logic for adding components is duplicated and exactly the same.</li><li><strong>Difficulty Extending Functionality</strong>: If in the future another type of component, like <code>Utensil</code>, needs to be added, it would be necessary to add another method (<code>addUtensil</code>) and modify the <code>showDetails</code> logic to include it. This makes the code less flexible and harder to maintain.</li><li><strong>Violation of the Liskov Substitution Principle</strong>: The <code>addIngredient</code> and <code>addRecipe</code> methods do not allow for treating all components uniformly. This violates the Liskov Substitution Principle, one of the SOLID principles, since <code>Recipe</code> and <code>Ingredient</code> cannot be used interchangeably through a common interface.</li></ol><p>These are precisely the problems we are going to solve with the <em>Composite</em> pattern. However, before we move on to the solution, let’s also look at the client code that would use this solution.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { Ingredient } from &quot;./ingredient&quot;;
import { Recipe } from &quot;./recipe&quot;;

const ingredient1 = new Ingredient(&quot;Flour&quot;, &quot;2 cups&quot;);
const ingredient2 = new Ingredient(&quot;Eggs&quot;, &quot;3&quot;);
const recipe = new Recipe(&quot;Cake&quot;);
recipe.addIngredient(ingredient1);
recipe.addIngredient(ingredient2);

const ingredient3 = new Ingredient(&quot;Milk&quot;, &quot;1 cup&quot;);
const compositeRecipe = new Recipe(&quot;Cake with Milk&quot;);
compositeRecipe.addRecipe(recipe);
compositeRecipe.addIngredient(ingredient3);

console.log(compositeRecipe.showDetails());
</code></pre>
<!--kg-card-end: markdown--><p>First, we see that we are creating several ingredients and a recipe for a cake. We have to link the ingredients to the cake through the <code>addIngredient</code> method.</p><p>On the other hand, if we want to create a <em>Cake with Milk</em>, we need to create a new recipe, add the <em>Milk</em> that we didn’t have in the previous recipe, and for the <em>Cake with Milk</em>, we need to nest the previously configured cake recipe. Here we can see that to add components, we don’t have a common interface, which even makes it difficult to work with the recipes.</p><p>Having outlined all the problems with this solution and the code we’ve analyzed, let’s introduce the <em>Composite</em> pattern to it.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="example-2-recipe-book-using-the-composite-pattern">Example 2: Recipe Book using the Composite Pattern</h2><p>To address the solution, the first thing we need to look at is how the UML class diagram of the problem evolves with the application of the <em>Composite</em> pattern.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/1000/0*g1-M0SiL6_s6Ybpy" class="kg-image" alt="Understanding the Composite Design Pattern"></figure><!--kg-card-end: image--><p>Let’s start by noting that we now have an interface named <code>RecipeComponent</code>, which defines the <code>showDetails</code> method as the common interface for all components. Both <code>ingredients</code> and <code>recipes</code> implement this interface. The <code>Ingredient</code> class does not undergo any changes in this solution. In fact, the <code>Ingredient</code> class is equivalent to the <code>Leaf</code> class in the pattern. On the other hand, the <code>Recipe</code> class changes considerably in the solution because it will now have an array of objects that satisfy the <code>RecipeComponent</code> interface. These will be both ingredients and recipes. Additionally, we will no longer have two methods to add ingredients or recipes; instead, there will be a single method called <code>addComponent</code> to perform these operations, and the <code>showDetails</code> method will be implemented.</p><p>Of course, let’s go through the code step by step to see how the code has evolved and how the issues have been resolved.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">export interface RecipeComponent {
    showDetails(): string;
}
</code></pre>
<!--kg-card-end: markdown--><p>Let’s start by looking at the interface for the components. This interface will be implemented by both ingredients and recipes. Initially, we only define the <code>showDetails</code> method.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { RecipeComponent } from &quot;./recipe-component&quot;;

export class Ingredient implements RecipeComponent {
    name: string;
    amount: string;

    constructor(name: string, amount: string) {
        this.name = name;
        this.amount = amount;
    }

    showDetails(): string {
        return `Ingredient: ${this.name}, Amount: ${this.amount}`;
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>If we look at the <code>Ingredient</code> class, it is exactly the same as before, except that now we implement the <code>RecipeComponent</code> interface, which we did previously as well. Reviewing the class, we see that we have two attributes for each ingredient: the <code>name</code> and the <code>amount</code>. These two attributes are received through the constructor to create each instance, and finally, we have the <code>showDetails</code> method, which is responsible for displaying the information of each ingredient.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { RecipeComponent } from &quot;./recipe-component&quot;;

export class Recipe implements RecipeComponent {
    name: string;
    components: RecipeComponent[] = [];

    constructor(name: string) {
        this.name = name;
    }

    addComponent(component: RecipeComponent): void {
        this.components.push(component);
    }

    showDetails(): string {
        let details = `Recipe: ${this.name}\n`;

        this.components.forEach(component =&gt; {
            details += `  ${component.showDetails()}\n`;
        });

        return details;
    }
}

</code></pre>
<!--kg-card-end: markdown--><p>On the other hand, if we look at the class corresponding to the recipes, here we do find changes. We start by seeing that the attributes are now the name of the recipe and an array of objects that satisfy the <code>RecipeComponent</code> interface, meaning they could be both ingredients and recipes. The constructor only requires the <code>name</code> of the recipe and nothing else. Furthermore, we no longer have two methods to manage recipes and ingredients; instead, with a single method like <code>addComponent</code>, we add both recipes and ingredients, eliminating redundancy in the code. The last method we need to look at is <code>showDetails</code>. Now, instead of having several loops, we just need to traverse the data structure we have and invoke the <code>showDetails</code> method because we know that all objects satisfy the interface that introduces this method.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { Ingredient } from &quot;./ingredient&quot;;
import { Recipe } from &quot;./recipe&quot;;

// Usage
const ingredient1 = new Ingredient(&quot;Flour&quot;, &quot;2 cups&quot;);
const ingredient2 = new Ingredient(&quot;Eggs&quot;, &quot;3&quot;);
const recipe = new Recipe(&quot;Cake&quot;);
recipe.addComponent(ingredient1);
recipe.addComponent(ingredient2);

const ingredient3 = new Ingredient(&quot;Milk&quot;, &quot;1 cup&quot;);
const compositeRecipe = new Recipe(&quot;Cake with Milk&quot;);
compositeRecipe.addComponent(recipe);
compositeRecipe.addComponent(ingredient3);

console.log(compositeRecipe.showDetails());
</code></pre>
<!--kg-card-end: markdown--><p>We also need to look at the <code>client</code> class that uses the pattern. The first thing we would do now is to create instances of ingredients and the cake recipe again, which would have the two ingredients added through the <code>addComponent</code> method. Now, if we want to create a cake with milk, we simply need to create an ingredient that would be the milk and the cake with milk recipe, which would receive both the ingredient and the cake through the <code>addComponent</code> method. Finally, we would see the result through the <code>showDetails</code> method.</p><p>Now let’s move on to analyze how the <em>Composite</em> pattern relates to other design patterns.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="composite-pattern-relationship-with-other-patterns">Composite Pattern: Relationship with Other Patterns</h3><p>The <em>Composite</em> pattern integrates effectively with several other design patterns, each complementing its capabilities and extending its applicability in building complex and scalable systems. Below is a description of how the Composite pattern relates to other design patterns:</p><h3 id="decorator"><a href="https://carloscaballero.io/design-patterns-decorator">Decorator</a></h3><p>The <em>Composite</em> and <em><a href="https://carloscaballero.io/design-patterns-decorator">Decorator</a></em> patterns both structure objects recursively, allowing both simple and composite components to be treated uniformly. Both patterns use a common interface for the objects they manage. In <em>Composite</em>, leaves and composites implement the same interface. In <em><a href="https://carloscaballero.io/design-patterns-decorator">Decorator</a></em>, the decorated object and the decorator share the same interface.</p><p>While <em>Composite</em> is used to represent part-whole hierarchies, <em><a href="https://carloscaballero.io/design-patterns-decorator">Decorator</a></em> is employed to add additional responsibilities to an object dynamically without changing its structure. <a href="https://carloscaballero.io/design-patterns-decorator"><em>Decorator</em> </a>can be used in combination with <em>Composite</em> to add extra behaviors to components of a <em>Composite</em> structure.</p><h3 id="iterator"><a href="https://carloscaballero.io/design-patterns-iterator/">Iterator</a></h3><p>The <em><a href="https://carloscaballero.io/design-patterns-iterator/">Iterator</a></em> pattern complements the <em>Composite</em> pattern by providing a uniform way to traverse elements of the composite structure without knowing its internal structure. Both patterns promote a common interface for handling collections of objects. <em>Composite</em> organizes objects into a hierarchy, while <em><a href="https://carloscaballero.io/design-patterns-iterator/">Iterator</a></em> allows for sequential traversal of these objects.</p><p><em>Composite</em> is used to build complex hierarchical structures, and <em><a href="https://carloscaballero.io/design-patterns-iterator/">Iterator</a></em> can be used with <em>Composite</em> to navigate this structure transparently, facilitating manipulation and access to the components.</p><h3 id="visitor">Visitor</h3><p>The <em>Visitor</em> pattern allows for defining new operations on a <em>Composite</em> structure without modifying the component classes, facilitating the extension of functionalities. Both patterns operate on an object structure. <em>Composite</em> facilitates part-whole hierarchies management, while <em>Visitor</em> facilitates the execution of operations on the components of that structure.</p><p><em>Composite</em> is used to create object hierarchies, while <em>Visitor</em> can be applied to these hierarchies to define new operations, allowing operations to change without altering the component classes.</p><h3 id="flyweight"><a href="https://carloscaballero.io/understanding-the-flyweight-design-pattern/">Flyweight</a></h3><p>The <em><a href="https://carloscaballero.io/understanding-the-flyweight-design-pattern/">Flyweight</a></em> pattern can be used with <em>Composite</em> to efficiently handle a large number of similar objects by sharing intrinsic states. Both patterns aim to optimize resource usage. <em>Composite</em> organizes objects into hierarchical structures, and <em><a href="https://carloscaballero.io/understanding-the-flyweight-design-pattern/">Flyweight</a></em> reduces memory usage by sharing common components among objects.</p><p><em>Composite</em> is used to organize objects into part-whole hierarchies. <em><a href="https://carloscaballero.io/understanding-the-flyweight-design-pattern/">Flyweight</a></em> can be used within a <em>Composite</em> to reduce the memory needed by sharing common components among multiple instances.</p><h3 id="builder"><a href="https://carloscaballero.io/understanding-design-patterns-builder">Builder</a></h3><p>The <em><a href="https://carloscaballero.io/understanding-design-patterns-builder">Builder</a></em> pattern can be used to construct <em>Composite</em> structures incrementally and in a controlled manner. Both patterns simplify the creation of complex structures. <em>Composite</em> organizes objects into hierarchies, and <em><a href="https://carloscaballero.io/understanding-design-patterns-builder">Builder</a></em> facilitates the step-by-step construction of these hierarchies.</p><p><em>Composite</em> is used to represent complex hierarchical structures, while <em><a href="https://carloscaballero.io/understanding-design-patterns-builder">Builder</a></em> can be used to assemble these structures in a controlled way, ensuring that each component is added correctly.</p><h3 id="chain-of-responsibility"><a href="https://carloscaballero.io/understanding-the-chain-of-responsibility-design-pattern/">Chain of Responsibility</a></h3><p>The <em><a href="https://carloscaballero.io/understanding-the-chain-of-responsibility-design-pattern/">Chain of Responsibility</a></em> pattern can be used in a <em>Composite</em> structure to propagate requests through the components of the hierarchy. Both patterns handle distributed responsibilities. <em>Composite</em> organizes objects into a part-whole structure, and <em><a href="https://carloscaballero.io/understanding-the-chain-of-responsibility-design-pattern/">Chain of Responsibility</a></em> allows for request handling through a chain of objects.</p><p><em>Composite</em> is used to organize objects in a hierarchy. <a href="https://betterprogramming.pub/understanding-the-chain-of-responsibility-design-pattern-2f44cdff61e5" rel="noopener"><em>Chain of Responsibility</em></a> can be used to handle requests within this structure, allowing requests to propagate from one component to another until one that can handle them is found.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="conclusions">Conclusions</h2><p>Overall, the <em>Composite</em> pattern is a valuable tool for designing systems that manage complex hierarchies of objects, especially when aiming for:</p><ul><li><strong>Uniform Treatment of Objects and Compositions</strong>: It allows for the uniform treatment of individual objects (leaves) and combinations of objects (composites). This simplifies the handling of complex hierarchical structures by providing a common interface.</li><li><strong>Flexibility and Reusability</strong>: Individual and composite components implement the same interface, allowing for easy reuse and reorganization of components. This facilitates the modification and expansion of the structure without affecting other parts of the system.</li><li><strong>Ease of Maintenance</strong>: By treating individual and composite objects in the same manner, the code becomes easier to maintain and understand. Modifications to the structure or components can be made without affecting the rest of the system.</li><li><strong>Simplification of Client Code</strong>: Clients can treat composite and simple objects in the same way, reducing the complexity of the code that interacts with the hierarchical structure.</li></ul><p>However, the use of the <em>Composite</em> pattern also has some disadvantages:</p><ul><li><strong>Increased Implementation Complexity</strong>: The composite structure can make the system design more complex, especially when managing multiple levels of composition and aggregation.</li><li><strong>Potential Performance Loss</strong>: Navigating and managing a deep hierarchical structure can introduce performance overhead, particularly if aggregation and removal operations are performed frequently.</li><li><strong>Difficulty in Restricting Components</strong>: In some cases, it may be challenging to restrict the types of components that can be added to a composite, which could lead to a less secure or less clear design.</li></ul><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><p>The most important thing about the <em>Composite</em> pattern is not its specific implementation, but the ability to recognize the problem that this pattern can solve and when <strong>it can be applied.</strong> The specific implementation is not that important, as it will vary depending on the programming language used.</p><p>See this <a href="https://github.com/Caballerog/blog/tree/master/composite-pattern" rel="noopener">GitHub repo</a> for the full code.</p>]]></content:encoded></item><item><title><![CDATA[Understanding the Proxy Design Pattern]]></title><description><![CDATA[<p>There are 23 classic design patterns described in the original book <a href="https://amzn.to/3VN3Ygd" rel="noopener ugc nofollow"><em><em>Design Patterns: Elements of Reusable Object-Oriented Software</em></em></a>. These patterns provide solutions to particular problems often repeated in software development.</p><p>In this article, I am going to describe how the <em><em>Flyweight</em></em> pattern works and when it should be applied.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="proxy-basic-idea">Proxy:</h3>]]></description><link>https://www.carloscaballero.io/understanding-the-proxy-design-pattern/</link><guid isPermaLink="false">6661a2ac9c7a350001e7e399</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Carlos Caballero]]></dc:creator><pubDate>Tue, 11 Jun 2024 11:24:28 GMT</pubDate><media:content url="http://www.carloscaballero.io/content/images/2024/06/petter-lagson-NEtFkKuo7VY-unsplash.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://www.carloscaballero.io/content/images/2024/06/petter-lagson-NEtFkKuo7VY-unsplash.jpg" alt="Understanding the Proxy Design Pattern"><p>There are 23 classic design patterns described in the original book <a href="https://amzn.to/3VN3Ygd" rel="noopener ugc nofollow"><em><em>Design Patterns: Elements of Reusable Object-Oriented Software</em></em></a>. These patterns provide solutions to particular problems often repeated in software development.</p><p>In this article, I am going to describe how the <em><em>Flyweight</em></em> pattern works and when it should be applied.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="proxy-basic-idea">Proxy: Basic Idea</h3><p>The first thing we will do, as with the other design patterns, is to look at the definition offered by the book “Design Patterns” by the Gang of Four:</p><blockquote>Provide a surrogate or placeholder for another object to control access to it.</blockquote><p>A proxy can perform additional operations (such as controlled access, lazy loading, etc.) before accessing the real object. The most common uses of the proxy pattern according to its purpose are as follows:</p><ul><li><strong>Virtual Proxy</strong>: controls access to resources that are expensive to create, such as objects that require a lot of memory or processing time. It is used for lazy loading of an object.</li><li><strong>Protection Proxy</strong>: controls access to an object by providing different permissions to different users.</li><li><strong>Remote Proxy</strong>: allows access to an object that resides in a different address space. For example, this proxy could handle all the necessary communication between a client and a server on different machines.</li></ul><p>As we have done in the entire series of pattern videos, let’s start by looking at the UML class diagram to understand each of the elements of it.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/1000/0*p0sZ6Yl5XDSJk7vB" class="kg-image" alt="Understanding the Proxy Design Pattern"></figure><!--kg-card-end: image--><ol><li><strong>Subject</strong>: Defines a common interface for <code>RealSubject</code> and <code>Proxy</code> so that <code>Proxy</code> can be used in place of <code>RealSubject</code>.</li><li><strong>RealSubject</strong>: The real object that the proxy represents.</li><li><strong>Proxy</strong>: Maintains a reference that allows the proxy to access the <code>RealSubject</code>. Provides an identical interface to that of <code>Subject</code> so it can substitute <code>RealSubject</code>. Controls access to <code>RealSubject</code> and can be responsible for its creation and deletion.</li></ol><p>Now that we have a clear understanding of the basic structure, let’s see when this pattern is useful to us.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="proxy-pattern-when-to-use">Proxy Pattern: When to Use</h3><p>It The Proxy pattern is an excellent solution when we need to add a level of control or intermediation between the client and the real object. Here are some common situations where using the Proxy pattern can be beneficial:</p><ol><li><strong>Monitoring and Logging</strong>: If we need to record or monitor access to an object, a <code>Proxy</code> can intercept calls and add additional functionality, such as logging, without modifying the real object. This is useful for debugging, auditing, and usage analysis.</li><li><strong>Access Control</strong>: When we need to control access to an object, such as restricting who can interact with it or under what conditions. For example, in a system with different permission levels, a <em>Protection Proxy </em>can ensure that only authorized users can perform certain operations.</li><li><strong>Lazy Loading</strong>: If creating an object is costly in terms of resources and time, a <em>Virtual Proxy</em> can defer the creation of the object until it is really necessary. This is useful for optimizing performance and reducing resource consumption.</li><li><strong>Remote Access</strong>: In distributed applications where objects reside on different machines or processes, a <em>Remote Proxy</em> can handle all communication and data transfer, providing a local interface to the remote object. This simplifies interaction and hides the complexity of network communication.</li><li><strong>Resource Optimization</strong>: When handling heavy objects or costly resources, a <code>Proxy</code> can manage the object’s lifecycle, such as creation and destruction, to optimize the use of system resources.</li></ol><p>In summary, the <em>Proxy</em> pattern is useful in situations where additional control is needed, resource usage needs to be optimized, or interaction with remote objects needs to be facilitated. Now, let’s look at some examples of this pattern in application.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="proxy-pattern-examples">Proxy Pattern: Examples</h3><p>Next, we will illustrate the proxy pattern with several useful use cases:</p><ol><li><strong>Basic Structure of the Proxy Pattern</strong>: In this example, we will translate the theoretical UML diagram into TypeScript code to identify each of the classes involved in the pattern.</li><li>From the basic schema, we will create different types of proxies to understand many of the uses, so we will implement the <strong>logger</strong> proxy, <strong>security</strong> proxy,<strong> lazy loadin</strong>g proxy,<strong> remote access</strong> proxy, and <strong>caching</strong> proxy.</li></ol><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="example-1-basic-structure-of-the-proxy-pattern">Example 1: Basic Structure of the Proxy Pattern</h3><p>As always, the starting point is the UML class diagram to define each of the elements. This first class diagram is the same as the one we explained at the beginning of the post, and we won’t repeat the explanation here to avoid making the post too long.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/1000/0*KfeCr1XNO7r-0qBc" class="kg-image" alt="Understanding the Proxy Design Pattern"></figure><!--kg-card-end: image--><p>However, what we will do is review the implementation of it using the TypeScript programming language.</p><p>Let’s start with the Subject interface. This interface defines the contract that both the <code>RealSubject</code> and the <code>Proxy</code> must fulfill. This is evident since the proxy will intercept the <code>RealSubject</code> and must comply with the same interface.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">interface Subject {
    operation(): void;
}
</code></pre>
<!--kg-card-end: markdown--><p>On one hand, the <code>RealSubject</code> class only implements the methods to fulfill the <code>Subject</code> interface.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">class RealSubject implements Subject {
    operation(): void {
        console.log('RealSubject: Handling operation.');
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>On the other hand, we see that the <code>Proxy</code> class has an instance of <code>RealSubject</code> through composition, and in this example, we will accomplish this through the constructor. Although we could have used an accessor method to perform this composition. If we focus on the <code>operation</code> method, which is the one we need to implement to satisfy the <code>Subject</code> interface, we are simply invoking the <code>operation</code> method of the <code>Subject</code> instance. Obviously, as we are showing it, we are doing absolutely <em>NOTHING</em>, but it is precisely here where we would have the interception of the real method, and where we would implement the logic that we want the proxy to perform.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">class Proxy implements Subject {
    private realSubject: RealSubject;

    constructor(realSubject: RealSubject) {
        this.realSubject = realSubject;
    }

    operation(): void {
        // Different actions can be performed here
        this.realSubject.operation();
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>Lastly, we would have the client that would interact directly with the <code>Proxy</code> and not with the <code>RealSubject</code>. However, to illustrate the difference in the client, it would be that initially, the client would interact directly with <code>RealSubject</code>, but when we introduce the <em>Proxy</em> pattern, we would switch to interacting with the <code>Proxy</code> class instead of the <code>RealSubject</code> class.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">console.log('Client: Executing the client code with a real subject:');
const realSubject = new RealSubject();
realSubject.operation()

console.log('');

console.log('Client: Executing the same client code with a proxy:');
const proxy = new Proxy(realSubject);
proxy.operation();
</code></pre>
<!--kg-card-end: markdown--><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="example-2-different-types-of-proxies">Example 2: Different Types of Proxies</h3><p>In this example, we are going to create five different types of proxies to cover various use cases where the <em>Proxy</em> pattern is useful. Our examples will be simple but will give us the intent of the pattern, which is what really matters: having a recurring problem and how the pattern can help us solve it.</p><p>The UML class diagram for this proposal would be as follows:</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/1000/0*Uc4OBHFj-06CAy7A" class="kg-image" alt="Understanding the Proxy Design Pattern"></figure><!--kg-card-end: image--><p>We start by seeing that we have the <code>Subject</code> interface and the <code>RealSubject</code> class, which remain exactly the same as in the previous case, an interface that defines the contract that both <code>RealSubject</code> and the proxies must fulfill.</p><p>On the other hand, we have a package with different <code>Proxies</code>. In our case, we start with the <code>LoggingProxy</code> class, which will act to monitor access to a subject, <code>LazyProxy</code> which will delegate the creation of the subject object until it is requested, <code>RemoteProxy</code> which will load objects from an external and remote environment such as a backend, and <code>AccessProxy</code> which focuses on validating that a user can access the object.</p><p>On the other hand, we have a different <code>Subject</code> and <code>RealSubject</code>, which we have called <code>SubjectCache</code> and <code>RealSubjectCache</code> because the interface is different. In this case, we will have a <code>request</code> operation that receives a parameter, and therefore the object to which we apply the proxy will be <code>RealSubjectCache</code>. Finally, we have the proxy called <code>CacheProxy</code>, which will store the subjects that are requested from an external resource, and if this subject has already been previously loaded, it will be stored to speed up its loading.</p><p>So, let’s start with the implementation of these proxies.</p><h4 id="logging-proxy">Logging Proxy</h4><p>Let’s quickly review the <code>Subject</code> interface and the <code>RealSubject</code> to check that we still have a very simple interface, where a single operation called <code>operation</code> is defined, and as the <code>RealSubject</code> method implements this interface, we are just showing a trace message to know that we have passed through the <code>RealSubject</code>.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">export interface Subject {
    operation(): void;
}
</code></pre>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { Subject } from &quot;./subject.interface&quot;;

export class RealSubject implements Subject {
    operation(): void {
        console.log('RealSubject: Handling operation.');
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>Now let’s start by looking at the first proxy, and the simplest of all we will see, this would be the <code>LoggingProxy</code>. This proxy is exactly the same as the book example (Gang of Four), but now in the <code>operation</code> method, we have added a private method called <code>logAccess</code> which would store or communicate to the monitoring system that the proxy has been accessed.</p><p>In our particular case, we will just show on the screen that we have accessed it, and the next thing the proxy would do is invoke the <code>RealSubject</code> method. That is, this proxy would only add extra functionality before executing the <code>RealSubject</code> method.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { RealSubject, Subject } from &quot;../subjects/&quot;;

export class LoggingProxy implements Subject {
    private realSubject: RealSubject;

    constructor(realSubject: RealSubject) {
        this.realSubject = realSubject;
    }

    operation(): void {
        this.logAccess();
        this.realSubject.operation();
    }

    private logAccess(): void {
        console.log('LoggingProxy: Logging access to RealSubject.');
    }
}
</code></pre>
<!--kg-card-end: markdown--><h4 id="access-proxy">Access Proxy</h4><p>The next proxy we address is <code>AccessProxy</code>, this proxy focuses on controlling which users or other elements with permission can access the <code>RealSubject</code>. For this example, the proxy stores a new private property that is the user’s role, which we communicate to the <code>Proxy</code> through the constructor.</p><p>If we now look at the <code>operation</code> method, we see that we have a <a href="https://betterprogramming.pub/refactoring-guard-clauses-2ceeaa1a9da" rel="noopener">guard clause</a>. In this case, if the <code>checkAccess</code> is not satisfied, the method will automatically return a message indicating that access to the resource is not allowed. Otherwise, we can execute the <code>RealSubject's</code> operation method.</p><p>If we look at the private <code>checkAccess</code> method, there is the access logic to the <code>RealSubject</code>, in our case, it simply means that the user’s role should be admin.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { RealSubject, Subject } from &quot;../subjects/&quot;;

export class AccessProxy implements Subject {
    private realSubject: RealSubject;
    private userRole: string;

    constructor(realSubject: RealSubject, userRole: string) {
        this.realSubject = realSubject;
        this.userRole = userRole;
    }

    operation(): void {
        if (!this.checkAccess()) {
            return console.log('AccessProxy: Access denied.'); 
        }
        this.realSubject.operation();
    }

    private checkAccess(): boolean {
        console.log(`AccessProxy: Checking access for role ${this.userRole}.`);
        return this.userRole === 'admin';
    }
}
</code></pre>
<!--kg-card-end: markdown--><h4 id="lazy-proxy">Lazy Proxy</h4><p>Very similar in implementation that <code>AccessProxy</code> but with a very different objective, we have the <code>LazyProxy</code>. In this case, we will use the proxy to delay the creation of the <code>RealSubject</code> until the moment the <code>operation</code> method is executed.</p><p>First, we notice that this proxy does not receive the <code>RealSubject</code> through the constructor, but it is responsible for instantiating it in the <code>operation</code> method.</p><p>The first thing it does is check if the instance has a value other than <code>null</code>, in which case it is instantiated, and then the subject’s <code>operation</code> method is invoked.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { RealSubject, Subject } from &quot;../subjects/&quot;;

export class LazyProxy implements Subject {
    private realSubject: RealSubject | null = null;

    operation(): void {
        if (this.realSubject === null) {
            this.realSubject = new RealSubject();
        }
        this.realSubject.operation();
    }
}
</code></pre>
<!--kg-card-end: markdown--><h4 id="remote-proxy">Remote Proxy</h4><p>The next proxy is a bit more complex than the previous one but follows the same idea. We are talking about the <strong>remote proxy</strong>.</p><p>In this proxy, if we look at the <code>operation</code> method, we would have a solution very similar to the previous one, but now instead of directly creating the <code>RealSubject</code> if the instance does not exist in the proxy, we invoke a method that will remotely connect to retrieve the <code>RealSubject</code>. The <code>connectToRemote</code> method simulates an HTTP request or an external resource. In this case, we connect to the URL passed as an argument to the <code>fetch</code> method. As we know, in JavaScript, this method returns a <code>Promise</code>, which we can wait for and retrieve its result from the external resource with the reserved word <code>await</code>. We then only check that the request to the external resource did not respond with the value <code>ok</code>, and in that case, we return an <code>error</code>, using a <a href="https://betterprogramming.pub/refactoring-guard-clauses-2ceeaa1a9da" rel="noopener">guard clause</a> again.</p><p>We then simulate a small delay in the connection using promises and <code>setTimeout</code>. This code will not exist in production code because here we are only delaying execution for one second, to finally create the <code>RealSubject</code>. In a real scenario, the <code>RealSubject</code> would be constructed from the information retrieved from the requested HTTP resource.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { RealSubject, Subject } from &quot;../subjects/&quot;;

export class RemoteProxy implements Subject {
    private realSubject: RealSubject | null = null;
    private readonly remoteServerUrl: string = 'https://jsonplaceholder.typicode.com/posts/1';

    async operation(): Promise&lt;void&gt; {
        if (this.realSubject === null) {
            await this.connectToRemote();
        }
        if (this.realSubject) {
            this.realSubject.operation();
        }
    }

    private async connectToRemote(): Promise&lt;void&gt; {
        console.log('RemoteProxy: Connecting to remote server...');
        // Simulate HTTP request to connect to remote server

        const response = await fetch(this.remoteServerUrl);
        if (!response.ok) {
            return console.error('RemoteProxy: Failed to connect to remote server.');
        }

        // Simulate network delay
        await new Promise(resolve =&gt; setTimeout(resolve, 1000));
        console.log('RemoteProxy: Connected to remote server.');
        this.realSubject = new RealSubject(); 
    }
}
</code></pre>
<!--kg-card-end: markdown--><h4 id="cache-proxy">Cache Proxy</h4><p>The last proxy example we will see is a bit more complex than the previous ones and would be building a cache of subject objects. So, the first thing we will see is the <code>SubjectCache</code> and <code>RealSubjectCache</code> interface, which differ from the previous one since now <code>SubjectCache</code> instead of having an <code>operation</code> method without parameters, we will have a <code>request</code> method that receives a resource argument of type string, and this function returns a promise of strings. We already know that this method will be asynchronous.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">export interface SubjectCache {
    request(resource: string): Promise&lt;string&gt;;
}
</code></pre>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { SubjectCache } from  './subject-cache.interface';

export class RealSubjectCache implements SubjectCache {
    async request(resource: string): Promise&lt;string&gt; {
        // Simulate fetching resource from external API
        console.log(`RealSubject: Fetching resource from ${resource}`);
        // Simulate network delay
        await new Promise(resolve =&gt; setTimeout(resolve, 1000));
        return `Response from ${resource}`;
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>The <code>RealSubjectCache</code> class, which is the real implementation of this interface, simply simulates that a request is being made to an external resource or API. To do this, we simulate a delay of one second until we return the <code>String</code> with a message from this <code>Subject</code>. In this use case, we do not want to go to the server and have a latency of one second or even more, and what we want is that if the <code>Subject</code> has already been queried, we do not request it again, but store it in a data structure. So, in <code>CacheProxy</code>, we have an attribute called <code>cache</code>, which is a <code>Map</code> that contains as a key a character string, which will be the resource, and as a value another character string, which will be the string we get in response.</p><p>We could also store an object in more advanced examples. Now if we look at the <code>request</code> method of the proxy, we can see that what is being done is a check through an if, where it is being checked if the cache has an entry with the resource key. If so, we are not invoking the <code>RealSubject</code> but returning the value we have stored, that is, we are improving the response time, in exchange for hardware resources such as memory for having the <code>Map</code> data structure.</p><p>On the other hand, if the resource has not been queried, what we will do is invoke the <code>RealSubject</code> method to get a response. Here we will have the same result as if we did not have the proxy, but immediately afterward we store the returned value in the data structure, and finally, the value is returned as well.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { RealSubjectCache, SubjectCache } from &quot;../subjects/&quot;;

export class CacheProxy implements SubjectCache {
    private realSubject: RealSubjectCache;
    private cache: Map&lt;string, string&gt; = new Map();

    constructor(realSubject: RealSubjectCache) {
        this.realSubject = realSubject;
    }

    async request(resource: string): Promise&lt;string&gt; {
        if (this.cache.has(resource)) {
            console.log(`CacheProxy: Retrieving response from cache for ${resource}`);
            return this.cache.get(resource)!;
        } else {
            const response = await this.realSubject.request(resource);
            console.log(`CacheProxy: Caching response for ${resource}`);
            this.cache.set(resource, response);
            return response;
        }
    }
}

</code></pre>
<!--kg-card-end: markdown--><p>And so far several types of proxies that have surely given you ideas and circumstances in which you can apply the pattern. Now let’s see how this pattern relates to other design patterns</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="proxy-pattern-relationship-with-other-patterns">Proxy Pattern: Relationship with Other Patterns</h3><p>The <em>Proxy</em> pattern has connections with several other design patterns, as it can complement and enhance their functionality. Some of the most relevant relationships are:</p><ul><li><strong><a href="https://www.carloscaballero.io/design-patterns-decorator/">Decorator Pattern</a></strong>: The <em>Decorator</em> pattern and the <em>Proxy</em> pattern share a similar structure, as both patterns wrap an object to add functionality. However, while the <em>Decorator</em> focuses on dynamically adding additional behaviors, the <em>Proxy</em> focuses on controlling access to the object.</li><li><strong><a href="https://www.carloscaballero.io/design-patterns-adapter/">Adapter Pattern</a></strong>: Both patterns wrap another object but with different purposes. The <em>Adapter</em> is used to transform one interface into another, making an object compatible with an interface it otherwise could not use. The <em>Proxy,</em> on the other hand, controls access to the object.</li><li><strong><a href="https://www.carloscaballero.io/design-patterns-singleton/">Singleton Pattern</a></strong>: The <em>Proxy</em> can use the <em>Singleton</em> pattern to ensure that there is only one instance of the proxy, especially in situations where centralized control of access to a shared resource is desired.</li><li><strong><a href="https://www.carloscaballero.io/understanding-design-patters-factory-method/">Factory Method Pattern</a></strong>: A <em>Proxy</em> can be created using the <em>Factory Method</em> pattern to manage the creation of proxies in a flexible and decoupled manner. This is useful for maintaining a clean and modular code structure.</li><li><strong><a href="https://www.carloscaballero.io/understanding-the-flyweight-design-pattern/">Flyweight Pattern</a></strong>: A <em>Proxy</em> can wrap a <em>Flyweight</em> object, providing additional control over access to shared objects. This is useful when more granular management of <em>Flyweight</em> objects is needed, such as memory management or lifecycle control.</li><li><strong>Composite Pattern</strong>: The <em>Proxy</em> can work with the <em>Composite</em> pattern to handle hierarchical structures of objects where access to subcomponents needs to be controlled individually. This can be useful in systems where the object structure is complex and detailed access control is required.</li></ul><p>By leveraging these relationships with other patterns, the <em>Proxy</em> pattern can improve the modularity, scalability, and maintainability of a system while providing additional control over the access and management of objects.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="conclusions">Conclusions</h3><p>The <em>Proxy</em> pattern offers a versatile and effective solution for systems that require additional control over object access. By providing an intermediary that handles various responsibilities such as access control, lazy loading, and remote communication, the <em>Proxy</em> pattern can significantly enhance the system’s security, performance, and flexibility.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><p>The most important thing about the <em>Proxy</em> pattern is not its specific implementation, but the ability to recognize the problem that this pattern can solve and when <strong>it can be applied.</strong> The specific implementation is not that important, as it will vary depending on the programming language used.</p><p>See this <a href="https://github.com/Caballerog/blog/tree/master/proxy-pattern" rel="noopener">GitHub repo</a> for the full code.</p>]]></content:encoded></item><item><title><![CDATA[Understanding the Flyweight Design Pattern]]></title><description><![CDATA[<p>There are 23 classic design patterns described in the original book <a href="https://amzn.to/3VN3Ygd" rel="noopener ugc nofollow"><em><em>Design Patterns: Elements of Reusable Object-Oriented Software</em></em></a>. These patterns provide solutions to particular problems often repeated in software development.</p><p>In this article, I am going to describe how the <em><em>Flyweight</em></em> pattern works and when it should be applied.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h1 id="flyweight-basic-idea">Flyweight:</h1>]]></description><link>https://www.carloscaballero.io/understanding-the-flyweight-design-pattern/</link><guid isPermaLink="false">665ee5c59c7a350001e7e32a</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Carlos Caballero]]></dc:creator><pubDate>Thu, 06 Jun 2024 11:19:30 GMT</pubDate><media:content url="http://www.carloscaballero.io/content/images/2024/06/connor-coyne-OgqWLzWRSaI-unsplash--6-.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://www.carloscaballero.io/content/images/2024/06/connor-coyne-OgqWLzWRSaI-unsplash--6-.jpg" alt="Understanding the Flyweight Design Pattern"><p>There are 23 classic design patterns described in the original book <a href="https://amzn.to/3VN3Ygd" rel="noopener ugc nofollow"><em><em>Design Patterns: Elements of Reusable Object-Oriented Software</em></em></a>. These patterns provide solutions to particular problems often repeated in software development.</p><p>In this article, I am going to describe how the <em><em>Flyweight</em></em> pattern works and when it should be applied.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h1 id="flyweight-basic-idea">Flyweight: Basic Idea</h1><p>First, let’s see the definition provided by the <a href="https://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional-ebook/dp/B000SEIBB8" rel="noopener ugc nofollow">Gang of Four book</a>:</p><blockquote>A flyweight is a shared object that can be used in multiple contexts simultaneously. The flyweight acts as an independent object in each context; it’s indistinguishable from an instance of the object that is not shared.</blockquote><p>On the other hand, flyweight objects cannot make assumptions about the context in which they operate. The key concept here is the distinction between <em><em>intrinsic</em></em> and <em><em>extrinsic</em></em> state. Intrinsic state is stored in the flyweight; it consists of information that is independent of the flyweight’s context, allowing it to be shared. Extrinsic state depends on the flyweight’s context and varies with it, therefore, it cannot be shared. Client objects are responsible for passing the extrinsic state to the flyweight when it is needed.</p><p>Next, let’s take a look at the UML class diagram for this pattern to understand each of its elements.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://miro.medium.com/v2/resize:fit:770/0*vDnqV2TP0jnPq97V" class="kg-image" alt="Understanding the Flyweight Design Pattern"></figure><!--kg-card-end: image--><p>The <em><em>Flyweight</em></em> pattern typically includes the following elements:</p><ul><li><strong><strong>Flyweight</strong></strong>: Defines the interface for objects that can be shared. It contains the intrinsic states that are shared among several objects.</li><li><strong><strong>Concrete Flyweight</strong></strong>: Implements the <em><em>Flyweight</em></em> interface and stores the intrinsic states. These objects are shared among multiple contexts.</li><li><strong><strong>Unshared Concrete Flyweight</strong></strong>: Represents objects that cannot be shared. Although they do not share their state, they can contain references to other Flyweight objects.</li><li><strong><strong>Flyweight Factory</strong></strong>: Manages a set of Flyweight objects. It ensures that Flyweight objects are shared properly and provides methods to obtain instances of Flyweights.</li><li><strong><strong>Client</strong></strong>: Maintains references to the Flyweights and calculates or stores the extrinsic states (those that are not shared and can vary between objects).</li></ul><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h1 id="flyweight-pattern-when-to-use-it">Flyweight Pattern: When to Use It</h1><p>The <em><em>Flyweight</em></em> pattern is an excellent solution when dealing with systems that need to create and manage a large number of similar objects, which can result in high memory consumption if not managed properly. Below are some common situations where using the <em><em>Flyweight</em></em> pattern can be beneficial:</p><ol><li><strong><strong>Objects with shared states:</strong></strong> When we have a large number of objects that share significant parts of their state with each other, such as text, images, or similar data, the <em><em>Flyweight</em></em> pattern allows sharing these common states among multiple instances, thereby reducing memory consumption.</li><li><strong><strong>Reduction of resource consumption</strong></strong>: If you want to reduce memory or other resource consumption in your system, the <em><em>Flyweight</em></em> pattern can be an effective solution. By sharing common parts of objects among multiple instances, unnecessary duplication of data is avoided, and system performance is optimized.</li><li><strong><strong>Facilitating object creation</strong></strong>: The <em><em>Flyweight</em></em> pattern facilitates the creation and management of a large number of objects by reusing existing instances instead of creating new ones each time they are needed. This can be especially useful in situations where object creation is resource-intensive in terms of computational resources.</li></ol><p>In summary, the <em><em>Flyweight</em></em> pattern is useful in situations where it is necessary to optimize memory and resource usage by sharing common parts of objects among multiple instances. Now, let’s look at examples of applying this pattern.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h1 id="flyweight-pattern-examples"><strong>Flyweight Pattern: Examples</strong></h1><p>Next, we will illustrate the <em><em>Flyweight</em></em> pattern with two examples:</p><ol><li><strong><strong>Basic Structure of the Flyweight Pattern</strong></strong>: In this example, we will translate the theoretical UML diagram into TypeScript code to identify each of the classes involved in the pattern.</li><li><strong><strong>A football statistics system</strong></strong>: We will have statistics for different teams, with hundreds of players where we need to objects to define the positions of the players and the teams they belong to. Here, we can see that we will have many objects that are shared, such as the specific positions of the players or the team.</li></ol><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h1 id="example-1-basic-structure-of-the-flyweight-pattern">Example 1: Basic Structure of the Flyweight Pattern</h1><p>As always, the starting point is the UML class diagram to define each of the elements. This first class diagram is the same one we explained at the beginning of the post, and we will not repeat the explanation here to avoid making the post too long.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://miro.medium.com/v2/resize:fit:770/0*yOhwlFLU39H7lOGq" class="kg-image" alt="Understanding the Flyweight Design Pattern"></figure><!--kg-card-end: image--><p>However, we will start implementing it step by step using the TypeScript programming language.</p><p>Let’s start with the <code>Flyweight</code> interface. This interface defines the contract that any <code>Flyweight</code> in the system must follow. In this case, it only has one method called <code>operation</code>, which receives the extrinsic state of our problem as a parameter. This method is implemented by the concrete flyweights, both the shared and the unshared ones.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">export interface Flyweight {
    operation(extrinsicState: any): void;
}
</code></pre>
<!--kg-card-end: markdown--><p>The next class is the <code>ConcreteFlyweight</code>. In this class, we can see that we have a private attribute, which is the <em><em>intrinsic</em></em> state of our problem. As always, to simplify the example, this attribute is of type <code>string</code>. This state is received as a constructor parameter to store it internally in this class. Finally, we have the implementation of the <code>operation</code> method, which receives the <em><em>extrinsic</em></em> state and performs a <code>console.log</code> showing both states. Obviously, here we would have the business logic for our problem.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { Flyweight } from &quot;./flyweight&quot;;

export class ConcreteFlyweight implements Flyweight {
    private intrinsicState: string;

    constructor(intrinsicState: string) {
        this.intrinsicState = intrinsicState;
    }

    public operation(extrinsicState: any): void {
        console.log(`ConcreteFlyweight: Intrinsic State = ${this.intrinsicState}, Extrinsic State = ${extrinsicState}`);
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>On the other hand, the <code>UnsharedConcreteFlyweight</code> class is the representation of the objects that are not shared in our problem. If we look at this class, we have a small variation; instead of having the <em><em>intrinsic</em></em> state stored, we have the entire state of the object. Obviously, again to simplify the example, it has been modeled as a <code>string</code>, but the conceptual difference is quite significant between <code>Flyweight</code> that share state and those that do not share state. Lastly, we have the implementation of the <code>operation</code> method, which displays the information of the <code>allState</code> attribute and the <em><em>extrinsic</em></em> state.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { Flyweight } from &quot;./flyweight&quot;;

// Unshared Concrete Flyweight
export class UnsharedConcreteFlyweight implements Flyweight {
    private allState: string;

    constructor(allState: string) {
        this.allState = allState;
    }

    public operation(extrinsicState: any): void {
        console.log(`UnsharedConcreteFlyweight: All State = ${this.allState}, Extrinsic State = ${extrinsicState}`);
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>Up to this point, we have the <em><em>Flyweight</em></em> pattern by definition. However, in most cases, this pattern includes a factory class that is responsible for creating the <code>Flyweight</code> objects. And it is precisely this class that we will look at next.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { ConcreteFlyweight } from &quot;./concrete-flyweight&quot;;
import { Flyweight } from &quot;./flyweight&quot;;

// Flyweight Factory
export class FlyweightFactory {
    private flyweights: Map&lt;string, Flyweight&gt; = new Map();

    public getFlyweight(key: string): Flyweight {
        if(this.flyweights.has(key)){
            console.log(`FlyweightFactory: Reusing existing flyweight for key = ${key}`);
            return this.flyweights.get(key)!;
        }
        
        this.flyweights.set(key,  new ConcreteFlyweight(key));
        console.log(`FlyweightFactory: Created new flyweight for key = ${key}`);
        return this.flyweights.get(key)!;
    }

    public listFlyweights(): void {
        console.log(`FlyweightFactory: I have ${this.flyweights.size} flyweights:`);
        for (const [key, _] of this.flyweights) {
            console.log(key);
        }
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>In this class, we need to have a data structure where we store the different <code>Flyweight</code> objects. In our case, we are using a map where the key is a string identifier, and the value is the stored <code>Flyweight</code> object.</p><p>The <code>getFlyweight</code> method is the key to this factory because it takes the key as an argument to retrieve the object from the data structure. As we can see in the first control block of the code, the <code>if</code> statement checks whether the data structure contains the object we are looking for, and if it does, we simply return it.</p><p>If we do not have the object in the data structure, a new <code>Flyweight</code> object is created using the <code>ConcreteFlyweight</code>constructor and stored in our data structure. The method concludes by returning the object we just created.</p><p>Therefore, we are implementing a small cache that will streamline the process of creating and retrieving objects. If the object already exists, we retrieve the one we have in memory and do not create duplicate objects. If the object does not exist, it is created only once.</p><p>The next method in the class, <code>listFlyweights</code>, simply iterates over the data structure where we have all the objects and displays the objects contained within it. We could have implemented any other business logic.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { FlyweightFactory } from &quot;./flyweight-factory&quot;;
import { UnsharedConcreteFlyweight } from &quot;./unshared-flyweight&quot;;

const factory = new FlyweightFactory();

// Create and use shared flyweights
const flyweight1 = factory.getFlyweight('A');
flyweight1.operation('First Call');

const flyweight2 = factory.getFlyweight('B');
flyweight2.operation('Second Call');

const flyweight3 = factory.getFlyweight('A');
flyweight3.operation('Third Call');

// Create and use unshared flyweights
const unsharedFlyweight1 = new UnsharedConcreteFlyweight('Unique State');
unsharedFlyweight1.operation('Fourth Call');

factory.listFlyweights();
</code></pre>
<!--kg-card-end: markdown--><p>Finally, let’s look at the client code that uses the design pattern. In the code, the first thing we do is create the factory, which is responsible for managing the <code>Flyweight</code> objects. Next, we retrieve an object with the value <code>A</code>. Internally, the pattern will create this object since it does not exist and store it in the data structure. Then, we can use the <code>operation</code> method. We do the same with the object with the value <code>B</code>. The application of the pattern comes when creating the third object, where we retrieve the value <code>A</code>, and in this case, no more resources are consumed since it is obtained directly from the data structure instead of being instantiated again.</p><p>On the other hand, showing that the instance of objects that do not share the state would be as simple as making instances of these objects and using the defined methods. To conclude, we show all the objects instantiated in the data structure through the <code>listFlyweights</code> method, and we can see that the object with the value <code>A</code> appears instantiated only once in our problem</p><h1 id="example-2-football-player-statistics-database-without-the-flyweight-pattern">Example 2: Football Player Statistics Database without the Flyweight Pattern</h1><p>In this example, we are going to create a database of football players where each player will have instances of other objects such as their positions and the team they belong to. Additionally, the players will have their own statistics on their performance in official matches.</p><p>Considering this problem, the UML class design that can be proposed is as follows:</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://miro.medium.com/v2/resize:fit:770/0*mZTte5B0dAB5f3Vd" class="kg-image" alt="Understanding the Flyweight Design Pattern"></figure><!--kg-card-end: image--><p>We can observe that we would have the <code>Player</code> class with its own attributes, such as <code>name</code>, <code>position</code>, <code>team</code>, and <code>statistics</code>. The attributes <code>position</code>, <code>team</code>, and <code>statistics</code> are not primitives but objects that have different attributes, which, of course, could have more logic and methods, implement interfaces, etc. However, as always, we are simplifying to properly understand the pattern. But at first glance, we can see that we have the <code>Player</code> class and, through composition, we encounter three classes that are related to it. These classes depend on the <code>Player</code>, meaning that if the <code>Player</code> disappears, the objects in the composition are also destroyed.</p><p>The client of this application is called <code>SportsSimulator</code>, which is the class that would have the data structure storing all the instances of the players and some methods to manage this data structure, such as <code>addPlayer</code>, which receives the arguments for creating players, and the <code>displayPlayers</code> method, which lists all the players in the software. We can observe that <code>SportsSimulator</code> is not responsible for creating objects such as position, team, or statistics but rather receives the information from some data source. The only thing we can know and guarantee is that the data has the corresponding attributes to be well-formed. This has been modeled with the package of <code>interfaces</code>, where we find the interfaces for position, team, and statistics.</p><p>Let’s proceed to see the implementation of this first solution, which <strong><strong>does NOT</strong></strong> use the <em><em>Flyweight</em></em> pattern, to detect where the resource leak is that we could improve with the pattern.</p><p>The first class we need to look at is the <code>Player</code> class, which is quite simple. If we observe, we have the four attributes that make up a <code>Player</code>, and through the constructor, we receive the parameters that allow us to internally store each attribute of this object. Additionally, we include a <code>toString</code> method, which we have renamed as <code>displayInfo</code>, that simply shows the information of the object.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { Position } from &quot;./position&quot;;
import { Stats } from &quot;./stats&quot;;
import { Team } from &quot;./team&quot;;

export class Player {
    private name: string;
    private position: Position;
    private team: Team;
    private stats: Stats;

    constructor(name: string, position: Position, team: Team, stats: Stats) {
        this.name = name;
        this.position = position;
        this.team = team;
        this.stats = stats;
    }

    public displayInfo(): void {
        console.log(`Player - Name: ${this.name}, Position: ${this.position.name} (${this.position.role}), Team: ${this.team.name} (Coach: ${this.team.coach}), Stats: [Goals: ${this.stats.goals}, Assists: ${this.stats.assists}, Matches: ${this.stats.matches}]`);
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>On the other hand, the <code>Position</code>, <code>Team</code>, and <code>Stats</code> classes do not contain any logic. Again, we repeat, this is didactic, and they should make sense as such to exist, but to simplify, we can see that they simply store the corresponding attributes of each type of object when they are constructed.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">export class Position {
    constructor(public name: string, public role: string) {}
}

export class Stats {
    constructor(public goals: number, public assists: number, public matches: number) {}
}

export class Stats {
    constructor(public goals: number, public assists: number, public matches: number) {}
}
</code></pre>
<!--kg-card-end: markdown--><p>The next class is <code>SportsSimulator</code>, which is responsible for storing the data structure. In this case, we would have an array of <code>Players</code>, which are built in the <code>addPlayer</code> method itself. This method receives as a parameter the necessary information to create instances of all the objects. However, what it receives are objects that satisfy the interface of <code>Position</code>, <code>Team</code>, and <code>Stats</code>, but these objects it receives are not instances of classes, but simply data.</p><p>Therefore, the three objects that the instance of the <code>Player</code> class required are created, and once created, they are added to the data structure.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { IPosition, IStats, ITeam } from &quot;./interfaces&quot;;
import { Player, Position, Stats, Team } from &quot;./models&quot;;

export class SportsSimulator {
    private players: Player[] = [];

    public addPlayer(name: string, position: IPosition, team: ITeam, stats: IStats): void {
        const positionPlayer = new Position(position.name, position.role);
        const teamPlayer = new Team(team.name, team.coach);
        const statsPlayer = new Stats(stats.goals, stats.assists, stats.passes);

        const player = new Player(name, positionPlayer, teamPlayer, statsPlayer);
        this.players.push(player);
    }

    public displayPlayers(): void {
        this.players.forEach(player =&gt; player.displayInfo());
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>As mentioned earlier, the interfaces simply specify the attributes that the plain objects passed as arguments must contain. We have done it this way because in TypeScript, we can quickly create plain objects, which allows us to avoid having a method signature for <code>addPlayer</code> with all the attributes of player, position, team, and statistics separated, but instead having them grouped by plain objects.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">export interface IPosition {
    name: string;
    role: string;
};

export interface ITeam {
    name: string;
    coach: string;
};

export interface IStats {
    goals: number;
    assists: number;
    passes: number;
};
</code></pre>
<!--kg-card-end: markdown--><p>Finally, we need to see the client code that uses all these classes.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { IPosition, IStats, ITeam } from &quot;./interfaces&quot;;

import { SportsSimulator } from &quot;./sports-simulator&quot;;

// Client Code
const simulator = new SportsSimulator();

const forward: IPosition = {name: 'Forward', role: 'Attacker'};
const midfielder: IPosition = {name: 'Midfielder', role: 'Support'};
const defender: IPosition = { name: 'Defender', role: 'Defender'};
const goalkeeper: IPosition = {name: 'Goalkeeper', role: 'Goalkeeper'};

const positions = [goalkeeper, defender, midfielder, forward]

const teams: ITeam[] = [
    { name: &quot;New Team&quot;, coach: &quot;Roberto Sedinho&quot; },
    { name: &quot;Furano FC&quot;, coach: &quot;Koujiro Hyuuga&quot; },
    { name: &quot;Toho Academy&quot;, coach: &quot;Kira Hiroto&quot; },
    { name: &quot;Nankatsu SC&quot;, coach: &quot;Tsubasa Ozora&quot; },
    { name: &quot;Otomo FC&quot;, coach: &quot;Shingo Aoi&quot; },
    { name: &quot;Hirado FC&quot;, coach: &quot;Hajime Taki&quot; },
    { name: &quot;Mamoru United&quot;, coach: &quot;Taro Misaki&quot; },
    { name: &quot;Meiwa FC&quot;, coach: &quot;Jun Misugi&quot; }
];

const captainTsubasaCharacters: string[] = [
    &quot;Tsubasa Ozora&quot;,
    &quot;Koujiro Hyuuga&quot;,
    &quot;Genzo Wakabayashi&quot;,
    &quot;Taro Misaki&quot;,
    &quot;Shingo Aoi&quot;,
    &quot;Hikaru Matsuyama&quot;,
    &quot;Jun Misugi&quot;,
    &quot;Ken Wakashimazu&quot;,
    &quot;Kazuo Tachibana&quot;,
    &quot;Masao Tachibana&quot;,
    &quot;Ryo Ishizaki&quot;,
    &quot;Kojiro Hyuga&quot;,
    &quot;Teppei Kisugi&quot;,
    &quot;Hiroshi Jito&quot;,
    &quot;Shun Nitta&quot;,
    &quot;Mamoru Izawa&quot;,
    &quot;Hanji Urabe&quot;,
    &quot;Shingo Takasugi&quot;,
    &quot;Mitsuru Sano&quot;,
    &quot;Makoto Soda&quot;
];


for(let i = 0; i &lt; 25*teams.length -1; i++){
    const team = teams[i % teams.length];

    const position = positions[i % positions.length];
    const playerName = captainTsubasaCharacters[i % captainTsubasaCharacters.length];
    const stats: IStats = {
        goals: Math.floor(Math.random() * 20),
        assists: Math.floor(Math.random() * 20),
        passes: Math.floor(Math.random() * 20),
    };

    simulator.addPlayer(playerName, position, team, stats);
}

simulator.displayPlayers();
</code></pre>
<!--kg-card-end: markdown--><p>The first thing we have to do is create the sports simulator. To do this, we simply need to instantiate the <code>SportsSimulator</code> class. Next, we have the data we are going to use in the problem. This data can come from any data source, whether it’s integration files, databases, or even entered by the user. So, first, we define the positions, which would be forward, midfielder, defender, and goalkeeper.</p><p>Next, we define exactly the same but for the teams. We would have an array of team objects that satisfy the conditions of having a name and a coach. If you’ve noticed the names of the teams, our database is based on the anime series <em><em>Captain Tsubasa</em></em>. So, we need to reflect the names of the players as they appeared in the original version of the anime.</p><p>The last of our client code is a simple loop that is creating the necessary information for each team to have twenty five players. For that, we simply iterate to retrieve the information and send it to the simulator through the <code>addPlayer</code> method, and that’s where our object-oriented design would begin. Obviously, as we have more and more players, we will have more resources consumed by the instantiation of objects.</p><p>So far, there wouldn’t be a problem until one day the software needs more memory and we have to redesign it, which is exactly what we are going to do, but using the <em><em>Flyweight</em></em> pattern.</p><h1 id="example-2-football-player-statistics-database-using-the-flyweight-pattern">Example 2: Football Player Statistics Database using the Flyweight Pattern</h1><p>The problems that arise in the solution without the <em><em>Flyweight</em></em> pattern are as follows:</p><ol><li><strong><strong>Excessive memory usage</strong></strong>: When many similar objects are created, each instance occupies its own space in memory. This can lead to very high memory consumption, especially if the objects have attributes that are repeated in multiple instances.</li><li><strong><strong>Data redundancy</strong></strong>: In the absence of the <em><em>Flyweight</em></em> pattern, data that is common to multiple objects is duplicated in each instance. This not only increases memory usage but also introduces redundancy that can complicate data maintenance and updating.</li><li><strong><strong>Degradation of the system when used</strong></strong>: Handling a large number of individual objects can degrade application performance, both in terms of processing time and resource consumption. Operations involving the manipulation of these objects can become slow and inefficient.</li><li><strong><strong>Difficulty in resource management</strong></strong>: Without the <em><em>Flyweight</em></em> pattern, managing resources shared among multiple instances of objects becomes more complicated. This can lead to consistency and synchronization problems, especially in concurrent or distributed applications. Implementing the <em><em>Flyweight</em></em> pattern can mitigate these problems by allowing the sharing of objects where possible, reducing redundancy, and optimizing memory and resource usage. Let’s start by seeing how the UML class diagram evolves.</li></ol><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://miro.medium.com/v2/resize:fit:770/0*wL7wWjU3bRYXqop7" class="kg-image" alt="Understanding the Flyweight Design Pattern"></figure><!--kg-card-end: image--><p>Let’s start by looking at the <code>Player</code> class. This class now does not directly relate to the <code>Position</code> and <code>Team</code> classes. Instead, there is now an intermediate class called <code>PositionFlyweight</code> and <code>TeamFlyweight</code>, each of which contains an aggregation of the <code>Position</code> and <code>Team</code> classes. Both flyweight classes implement the flyweight interface, which simply has a method called display to show information. These classes could be omitted if we didn’t have <em><em>extrinsic</em></em> states, but we’re demonstrating the pattern with different elements that could disappear depending on specific circumstances and problems.</p><p>Another key point in the diagram is that we have an abstract class that defines the different object factories. The <code>flyweightFactory</code> class is composed of a <code>Map</code> of objects that satisfy the <code>Flyweight</code> interface. This abstract class is extended by the <code>PositionFlyweight</code> and <code>TeamFlyweight</code> classes, which do have concreteness in their data structure. In one case, they store objects of the <code>PositionFlyweight</code> class, and in the other, objects of the <code>TeamFlyweight</code> class. Both implement the <code>getFlyweight</code> method, which allows us to create a new <code>PositionFlyweight</code> or <code>TeamFlyweight</code> object or retrieve it from the data structure.</p><p>As an exercise or appreciation of how design patterns intertwine, this method has an algorithm in which all steps are similar except one, which could allow us to implement the <a href="https://ccaballero.medium.com/design-patterns-template-method-5400dde7bb72" rel="noopener">template-method design pattern</a>, as we have seen in another post. However, we will duplicate code to simplify this example, as we are focusing on the <em><em>flyweight</em></em> pattern and not another. But what’s important is that we understand the purpose of each design pattern so that when they arise, we can think about how to adapt it to our problem.</p><p>Finally, we see that we have the <code>SportsSimulator</code> class, which will make use of both factories and will have the data structure of the players. Similarly to the previous example, the data will come from a data source where we only have the attributes without instantiation, and we can only guarantee that they have a series of attributes using the package of interfaces that has been defined.</p><p>Alright, let’s proceed to gradually review the implementation and how it has changed compared to the previous example to improve the application’s performance.</p><p>Let’s start with the code of the <code>Player</code> class, which instead of directly receiving <code>Position</code> and <code>Team</code> objects, now receives instances of <code>PositionFlyweight</code> and <code>TeamFlyweight</code> objects. Since <code>Stats</code> objects are not reused and are different for each class, they still maintain their direct relationship with the <code>Player</code> class. The <code>displayInfo</code> method is practically the same, only updating the invocation of the display method of the <code>positionFlyweight</code> object.</p><p>The <code>Stats</code> class undergoes no modification compared to the previous example since we are not applying any pattern or improvement there. This is because the statistics will not be reused among different players as the probability of reusing an object is low, and we would not benefit from this design pattern.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { PositionFlyweight } from &quot;../position-flyweight&quot;;
import { Stats } from &quot;./stats&quot;;
import { TeamFlyweight } from &quot;../team-flyweight&quot;;

export class Player {
    private name: string;
    private positionFlyweight: PositionFlyweight;
    private teamFlyweight: TeamFlyweight;
    private stats: Stats;

    constructor(name: string, positionFlyweight: PositionFlyweight, teamFlyweight: TeamFlyweight, stats: Stats) {
        this.name = name;
        this.positionFlyweight = positionFlyweight;
        this.teamFlyweight = teamFlyweight;

        this.stats = stats;
    }

    public displayInfo(): void {
        console.log(`Player - Name: ${this.name}, Stats: [Goals: ${this.stats.goals}, Assists: ${this.stats.assists}, Matches: ${this.stats.matches}]`);
        this.positionFlyweight.display(this.stats);
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>So, let’s move on to see the <code>PositionFlyweight</code> and <code>TeamFlyweight</code> classes.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { Flyweight } from &quot;./flyweight&quot;;
import { Position } from &quot;./models&quot;;

export class PositionFlyweight implements Flyweight {
    #position: Position; // Intrinsic State

    constructor(position: Position) {
        this.#position = position;
    }

    public display(extrinsicState: any): void {
        console.log(`Position: ${this.#position.name} (${this.#position.role})`);
    }

    public position(): Position {
        return this.#position;
    }
}
</code></pre>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { Flyweight } from &quot;./flyweight&quot;;
import { Team } from &quot;./models&quot;;

export class TeamFlyweight implements Flyweight {
    #team: Team; // Intrinsic State

    constructor(team: Team) {
        this.#team = team;
    }

    public display(extrinsicState: any): void {
        console.log(`Team: ${this.#team.name} (${this.#team.coach})`);
    }

    public team(): Team {
        return this.#team;
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>Both classes are very similar, as they simply have an object of the class they are encapsulating, <code>Position</code> or <code>Team</code>, which represent the <em><em>intrinsic</em></em> states of each class. In both cases, we have performed composition through the constructor, receiving the instance of the objects. The next thing we have implemented is the display method, which will receive the <em><em>extrinsic</em></em> state, if necessary, and will display information from both states through a <code>console.log</code>.</p><p>On the other hand, the <code>Position</code> and <code>Team</code> classes remain exactly the same as in the previous example; they are model classes without further changes.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">
import { Flyweight } from &quot;./flyweight&quot;;

// Flyweight Factory
export abstract class FlyweightFactory&lt;T&gt; {
    protected flyweights: Map&lt;string, Flyweight&gt; = new Map();
    
    public abstract getFlyweight(key: T): Flyweight;

    public listFlyweights(): void {
        console.log(`FlyweightFactory: I have ${this.flyweights.size} flyweights:`);
        for (const [key, _] of this.flyweights) {
            console.log(key);
        }
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>This class defines the two object factories that we will have. The data structure that will store the objects will be a <code>Map</code> that uses a string as the key and any object that implements the <code>Flyweight</code> interface as the value, which will be both <code>Position</code> and <code>Team</code>. The <code>getFlyweight</code> method is defined, which varies slightly depending on whether the factory is for <code>Position</code> or <code>Team</code> objects. This method is where we could improve by applying the <a href="https://ccaballero.medium.com/design-patterns-template-method-5400dde7bb72" rel="noopener">template-method pattern</a>, and we leave it as an exercise for you to do.</p><p>On the other hand, we see the <code>listFlyweight</code> method, which is exactly the same for both factories since all it does is iterate through the data structure.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { FlyweightFactory } from &quot;./flyweight.factory&quot;;
import { Position } from &quot;./models&quot;;
import { PositionFlyweight } from &quot;./position-flyweight&quot;;

export class PositionFlyweightFactory extends FlyweightFactory&lt;Position&gt; {

    protected flyweights: Map&lt;string, PositionFlyweight&gt; = new Map();

    public getFlyweight(position: Position): PositionFlyweight {
        const key = `${position.name}_${position.role}`;
        if(this.flyweights.has(key)) {
            console.log(`ConcreteFlyweightFactory: Reusing existing flyweight for Position = ${key}`);
            return this.flyweights.get(key)!;
        }

        this.flyweights.set(key, new PositionFlyweight(position));
        console.log(`PositionFlyweightFactory: Created new flyweight for Position = ${key}`);
        return this.flyweights.get(key)!;
    }
}
</code></pre>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { FlyweightFactory } from &quot;./flyweight.factory&quot;;
import { Team } from &quot;./models&quot;;
import { TeamFlyweight } from &quot;./team-flyweight&quot;;

export class TeamFlyweightFactory extends FlyweightFactory&lt;Team&gt; {

    protected flyweights: Map&lt;string, TeamFlyweight&gt; = new Map();

    public getFlyweight(team: Team): TeamFlyweight {
        const key = `team_${team.name}_coach_${team.coach}`;
        if(this.flyweights.has(key)) {
            console.log(`ConcreteFlyweightFactory: Reusing existing flyweight for Team = ${key}`);
            return this.flyweights.get(key)!;
        }

        this.flyweights.set(key, new TeamFlyweight(team));
        console.log(`PositionFlyweightFactory: Created new flyweight for Team = ${key}`);
        return this.flyweights.get(key)!;
    } 
}
</code></pre>
<!--kg-card-end: markdown--><p>If we look at the concrete implementations of the <code>PositionFlyweightFactory</code> and <code>TeamFlyweightFactory</code> classes, we can see that they are exactly the same, except for the type of object they are working with and the key used to select the object in the data structure. So, we’ll focus on one to explain both. Looking at <code>PositionFlyweight</code>, we see that this method first defines the key, which will be unique for each object and is formed by the values of each object. The next thing we need to do is check if this object exists in the data structure. If it does, we return it without needing to create a new object. But if it doesn’t exist in the data structure, what we do is create the object to store, store it, and finally return the object we just created.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { IPosition, IStats, ITeam } from &quot;./interfaces&quot;;
import { Player, Stats } from &quot;./models&quot;;

import { PositionFlyweightFactory } from &quot;./position-flyweight.factory&quot;;
import { TeamFlyweightFactory } from &quot;./team-flyweight.factory&quot;;

export class SportsSimulator {
    private players: Player[] = [];
    private positionFactory: PositionFlyweightFactory = new PositionFlyweightFactory();
    private teamFactory: TeamFlyweightFactory = new TeamFlyweightFactory();

    public addPlayer(name: string, position: IPosition, team: ITeam, stats: IStats): void {
        const positionFlyweight = this.positionFactory.getFlyweight(position);
        const teamFlyweight = this.teamFactory.getFlyweight(team);
        const statsPlayer = new Stats(stats.goals, stats.assists, stats.passes);
        const player = new Player(name, positionFlyweight, teamFlyweight, statsPlayer);
        this.players.push(player);
    }

    public displayPlayers(): void {
        this.players.forEach(player =&gt; player.displayInfo());
    }
}
</code></pre>
<!--kg-card-end: markdown--><p>Finally, we arrive at the <code>SportsSimulator</code> class, which is the database of our players. In this new version, in addition to having the data structure of the players, we need the two factories we just defined. The <code>addPlayer</code> method is where, instead of instantiating all the objects and composing them into the <code>Player</code>, we will use the factories to retrieve or create the objects based on the information. In this way, it will be these classes that decide whether new objects are instantiated or whether they are reused in the system.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { IPosition, IStats, ITeam } from &quot;./interfaces&quot;;

import { SportsSimulator } from &quot;./sports-simulator&quot;;

// Client Code
const simulator = new SportsSimulator();

const forward: IPosition = {name: 'Forward', role: 'Attacker'};
const midfielder: IPosition = {name: 'Midfielder', role: 'Support'};
const defender: IPosition = { name: 'Defender', role: 'Defender'};
const goalkeeper: IPosition = {name: 'Goalkeeper', role: 'Goalkeeper'};

const positions = [goalkeeper, defender, midfielder, forward]

const teams: ITeam[] = [
    { name: &quot;New Team&quot;, coach: &quot;Roberto Sedinho&quot; },
    { name: &quot;Furano FC&quot;, coach: &quot;Koujiro Hyuuga&quot; },
    { name: &quot;Toho Academy&quot;, coach: &quot;Kira Hiroto&quot; },
    { name: &quot;Nankatsu SC&quot;, coach: &quot;Tsubasa Ozora&quot; },
    { name: &quot;Otomo FC&quot;, coach: &quot;Shingo Aoi&quot; },
    { name: &quot;Hirado FC&quot;, coach: &quot;Hajime Taki&quot; },
    { name: &quot;Mamoru United&quot;, coach: &quot;Taro Misaki&quot; },
    { name: &quot;Meiwa FC&quot;, coach: &quot;Jun Misugi&quot; }
];

const captainTsubasaCharacters: string[] = [
    &quot;Tsubasa Ozora&quot;,
    &quot;Koujiro Hyuuga&quot;,
    &quot;Genzo Wakabayashi&quot;,
    &quot;Taro Misaki&quot;,
    &quot;Shingo Aoi&quot;,
    &quot;Hikaru Matsuyama&quot;,
    &quot;Jun Misugi&quot;,
    &quot;Ken Wakashimazu&quot;,
    &quot;Kazuo Tachibana&quot;,
    &quot;Masao Tachibana&quot;,
    &quot;Ryo Ishizaki&quot;,
    &quot;Kojiro Hyuga&quot;,
    &quot;Teppei Kisugi&quot;,
    &quot;Hiroshi Jito&quot;,
    &quot;Shun Nitta&quot;,
    &quot;Mamoru Izawa&quot;,
    &quot;Hanji Urabe&quot;,
    &quot;Shingo Takasugi&quot;,
    &quot;Mitsuru Sano&quot;,
    &quot;Makoto Soda&quot;
];


for(let i = 0; i &lt; 25*teams.length -1; i++){
    const team = teams[i % teams.length];

    const position = positions[i % positions.length];
    const playerName = captainTsubasaCharacters[i % captainTsubasaCharacters.length];
    const stats: IStats = {
        goals: Math.floor(Math.random() * 20),
        assists: Math.floor(Math.random() * 20),
        passes: Math.floor(Math.random() * 20),
    };

    simulator.addPlayer(playerName, position, team, stats);
}

simulator.displayPlayers();
</code></pre>
<!--kg-card-end: markdown--><p>Finally, the client that uses our <code>SportsSimulator</code> class is completely transparent and remains exactly the same, creating the data or receiving it from some data source, and sending it to <code>SportsSimulator</code>. But now, instead of having an explosion of objects consuming hardware resources, many of these objects will be reused, making the software lighter and able to continue providing service. In other words, we have achieved an optimization of RAM memory by making the objects lighter.</p><h1 id="flyweight-pattern-relationship-with-other-patterns"><strong>Flyweight Pattern: Relationship with Other Patterns</strong></h1><p>The <em><em>Flyweight</em></em> pattern has connections with several other design patterns, as it can complement and enhance their functionality. Some of the most relevant relationships include:</p><ol><li><strong><strong><a href="https://carloscaballero.io/design-patterns-singleton/">Singleton Pattern:</a> </strong></strong>The <em><em>Singleton</em></em> pattern can be used in conjunction with the <em><em>Flyweight</em></em> pattern to ensure that only one instance of the <em><em>Flyweight</em></em> Factory exists throughout the application. This ensures centralized management of <em><em>Flyweight</em></em> objects and prevents unnecessary creation of multiple factories.</li><li><strong><strong><a href="https://www.carloscaballero.io/understanding-design-patters-factory-method/">Factory Method Pattern</a>: </strong></strong>The implementation of the <em><em>Flyweight</em></em> Factory can leverage the <em><em>Factory Method</em></em> pattern to allow flexible and decoupled creation of <code>Flyweight</code> objects. This facilitates the creation and management of <code>Flyweight</code> object instances as needed in different parts of the system.</li><li><strong><strong>Composite Pattern: </strong></strong>The <em><em>Composite</em></em> pattern can be used in combination with the <em><em>Flyweight</em></em> pattern to represent hierarchical structures where some objects can be shared among multiple components. By using the <em><em>Flyweight</em></em> pattern for shared objects, memory consumption is significantly reduced, and system efficiency is improved.</li><li><strong><strong>Proxy Pattern: </strong></strong>The <em><em>Proxy </em></em>pattern can serve as a wrapper around a <code>Flyweight</code> object, allowing additional control over object access or lifecycle management. This can be useful when more granular control over access to <code>SharedFlyweight</code> objects is needed or when additional tasks need to be performed before or after accessing the object.</li></ol><p>By leveraging these relationships with other patterns, the <em><em>Flyweight</em></em> pattern can enhance the efficiency, scalability, and maintainability of a system while optimizing resource usage and promoting a clearer and more modular code structure.</p><h1 id="differences-and-similarities-with-other-patterns-singleton-and-prototype"><strong>Differences and Similarities with Other Patterns: Singleton and Prototype</strong></h1><p>Let’s examine the similarities and differences between the Singleton and Prototype design patterns since the <em><em>Flyweight</em></em> pattern is often confused with these two design patterns.</p><h2 id="singleton-pattern-differences"><strong>Singleton Pattern: Differences</strong></h2><ol><li>The <a href="https://carloscaballero.io/design-patterns-singleton/">Singleton pattern</a> is used to ensure that a class has only one instance and provides a global access point to that instance, while the <em><em>Flyweight</em></em> pattern is used to efficiently share a large number of objects.</li><li>In <a href="https://carloscaballero.io/design-patterns-singleton/">the Singleton pattern</a>, the emphasis is on having a single instance of a class, while in the <em><em>Flyweight</em></em> pattern, the emphasis is on efficiently sharing <em><em>intrinsic</em></em> states among multiple similar objects.</li></ol><h2 id="singleton-pattern-similarities"><em>Singleton Pattern: Similarities</em></h2><ol><li>Both patterns are related to efficient object management and resource optimization.</li><li>Both patterns can be used together to optimize the performance and efficiency of a system.</li></ol><h2 id="prototype-pattern-differences"><strong>Prototype Pattern: Differences</strong></h2><ul><li>The <em><em>Prototype</em></em> pattern is used to create new objects by duplicating an existing prototype, while the <em><em>Flyweight</em></em> pattern is used to share existing objects and minimize resource usage.</li><li>In the <em><em>Prototype</em></em> pattern, each instance can have its own unique state, while in the <em><em>Flyweight</em></em> pattern, part of the state can be shared among multiple instances.</li></ul><h2 id="prototype-pattern-similarities"><em>Prototype Pattern: Similarities</em></h2><ul><li>Both patterns are related to efficient object creation and resource optimization.</li><li>Both patterns can be used to reduce the overhead of object creation and improve system performance.</li></ul><p>Although the <em><em>Flyweight</em></em> pattern shares some similarities with the <em><em>Singleton</em></em> and <em><em>Prototype</em></em> patterns, it is important to understand their fundamental differences and how they can be used complementary to address different design problems.</p><h1 id="conclusions">Conclusions</h1><p>The <em><em>Flyweight</em></em> pattern provides an efficient and elegant solution for systems that need to manage a large number of similar objects. By sharing common parts of objects among multiple instances, significant resource optimization and system performance improvement are achieved.</p><p>The most important thing about the <em><em>Flyweight</em></em> pattern is not its specific implementation, but the ability to recognize the problem that this pattern can solve and when <strong><strong>it can be applied.</strong></strong> The specific implementation is not that important, as it will vary depending on the programming language used.</p><p>See this <a href="https://github.com/Caballerog/blog/tree/master/flyweight-pattern" rel="noopener ugc nofollow">GitHub repo</a> for the full code.</p>]]></content:encoded></item><item><title><![CDATA[Understanding the Mediator Design Pattern]]></title><description><![CDATA[<p>There are 23 classic design patterns described in the original book <a href="https://amzn.to/3VN3Ygd">Design Patterns: Elements of Reusable Object-Oriented Software</a>. These patterns provide solutions to particular problems often repeated in software development.</p><p>In this article, I am going to describe how the <em>Mediator</em> pattern works and when it should be applied.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="mediator-basic-idea">Mediator:</h2>]]></description><link>https://www.carloscaballero.io/understanding-the-mediator-design-pattern/</link><guid isPermaLink="false">664a4f7f9c7a350001e7e273</guid><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Carlos Caballero]]></dc:creator><pubDate>Fri, 31 May 2024 10:44:55 GMT</pubDate><media:content url="http://www.carloscaballero.io/content/images/2024/05/robin-glauser-zP7X_B86xOg-unsplash.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://www.carloscaballero.io/content/images/2024/05/robin-glauser-zP7X_B86xOg-unsplash.jpg" alt="Understanding the Mediator Design Pattern"><p>There are 23 classic design patterns described in the original book <a href="https://amzn.to/3VN3Ygd">Design Patterns: Elements of Reusable Object-Oriented Software</a>. These patterns provide solutions to particular problems often repeated in software development.</p><p>In this article, I am going to describe how the <em>Mediator</em> pattern works and when it should be applied.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="mediator-basic-idea">Mediator: Basic idea</h2><p>First, let’s see the definition provided by the <a href="https://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional-ebook/dp/B000SEIBB8">Gang of Four book</a>:</p><blockquote>Define an object that encapsulates how a set of objects interact. The mediator pattern promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.</blockquote><p>Next, let’s take a look at the UML class diagram for this pattern to understand each of its elements.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/1000/1*Z9E_ciorT486xqEz38EFsw.png" class="kg-image" alt="Understanding the Mediator Design Pattern"></figure><!--kg-card-end: image--><p>The <em>Mediator</em> pattern typically includes the following main elements:</p><ul><li><strong>Mediator:</strong> Defines the interface for communication with <code>Colleague</code> objects.</li><li><strong>Concrete Mediator:</strong> Implements the <code>Mediator</code> interface and coordinates communication between <code>Colleague</code> objects.</li><li><strong>Colleague:</strong> Defines the interface for communication with other colleagues through the mediator.</li><li><strong>Concrete Colleague:</strong> Implements the <code>Colleague</code> interface and communicates its needs to the mediator, reacting to messages from the mediator.</li></ul><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="mediator-pattern-when-to-use-it">Mediator Pattern: When to Use It</h2><p>The <em>Mediator</em> pattern is a good solution when we find ourselves with a system in which a set of objects communicate in a complex and direct way with each other, resulting in high coupling between them. Here are some common situations where using the <em>Mediator</em> pattern can be beneficial:</p><p><strong>1. Complex communication between multiple objects:</strong> As we have said, when we have several objects that need to communicate with each other in a complex and direct way, this can be difficult to understand and maintain. The <em>Mediator</em> pattern centralizes this complex communication into a single object, thus simplifying the communication flow and reducing coupling between objects.</p><p><strong>2. Reducing coupling:</strong> If you want to reduce coupling between the components of your system, the <em>Mediator</em> pattern can help. By centralizing communication between objects through a mediator, direct dependencies between objects are eliminated, making it easier to modify and maintain code.</p><p><strong>3. Facilitating component reusability:</strong> The <em>Mediator</em> pattern promotes the reusability of individual components by decoupling them from their interactions with other components. This allows objects to be more independent and therefore easier to reuse in different contexts or systems.</p><p>In summary, the <em>Mediator</em> pattern is useful in situations where it is necessary to reduce coupling between objects, simplify communication between them, and facilitate the maintenance and evolution of code in complex systems.</p><p>Let’s now move on to see examples of how to apply this pattern.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="mediator-pattern-examples">Mediator Pattern: Examples</h2><p>In this section, we will illustrate the Mediator pattern with two examples:</p><ol><li><strong>Basic Structure of the Mediator Pattern:</strong> In this example, we will translate the theoretical UML diagram into TypeScript code to identify each of the classes involved in the pattern.</li><li><strong>IoT Device Control System:</strong> In an Internet of Things (IoT) system where devices communicate directly with each other to coordinate their actions. If each device depends directly on other devices for communication, the system can become difficult to scale and maintain.</li></ol><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="example-1-basic-structure-of-the-mediator-pattern">Example 1: Basic Structure of the Mediator Pattern</h2><p>As always, the starting point is the UML class diagram. This UML class diagram is the same as the one we explained at the beginning of the post, and to lighten the post we will not explain it again as such. But we will start to see its implementation step by step.</p><p>Let’s start with the <code>Mediator</code> interface. This interface defines the contract that any mediator in the system must follow. In this case, it only has one method that we have called <code>notify</code> which receives the event sender (<code>sender</code>) and the event itself (<code>event</code>). This method is implemented by concrete mediators to handle communication between colleagues.</p><!--kg-card-begin: code--><pre><code class="language-typescript">import { Colleague } from "./colleague";

export interface Mediator {
    notify(sender: Colleague, event: string): void;
}</code></pre><!--kg-card-end: code--><p>The next class is the concrete mediator. This class implements the <code>Mediator</code> interface. It has references to the colleagues with which it will interact. In the <code>notify</code> method, the mediator receives an event from a colleague and decides how to handle it based on the sender. In our case, the solution has been modeled using a switch control structure in which, depending on the colleague, we invoke a request handler. In this example, we only display messages on the screen to know that the notification has arrived correctly.</p><!--kg-card-begin: code--><pre><code class="language-typescript">import { Colleague } from "./colleague";
import { Colleague1 } from "./colleague1";
import { Colleague2 } from "./colleague2";
import { Mediator } from "./mediator";

export class ConcreteMediator implements Mediator {
    private colleague1: Colleague1;
    private colleague2: Colleague2;

  
    constructor(colleague1: Colleague1, colleague2: Colleague2) {
      this.colleague1 = colleague1;
      this.colleague2 = colleague2;
    }
  
    notify(sender: Colleague, event: string): void {
        switch(sender){
            case this.colleague1: this.handleColleague1(event); break;
            case this.colleague2: this.handleColleague2(event); break;
            default: console.log("Unknown sender");
        }

    }
    private handleColleague1(event){
        console.log("Event received by ConcreteMediator from Colleague1: ", event);
        console.log("implements colleague1 logic");
        console.log("-----------------");
    }

    private handleColleague2(event){
        console.log("Event received by ConcreteMediator from Colleague1: ", event);
        console.log("implements colleague1 logic");
        console.log("-----------------");
    }
}</code></pre><!--kg-card-end: code--><p>The next thing would be to define the colleague interface, which is the contract that all colleagues in the system must follow. In this case, they have two methods: <code>setMediator</code>, to set the mediator they belong to, and <code>action</code>, to perform an action that can generate an event.</p><!--kg-card-begin: code--><pre><code class="language-typescript">import { Mediator } from "./mediator";

export interface Colleague {
    setMediator(mediator: Mediator): void;
    action(): void;
}</code></pre><!--kg-card-end: code--><p>What remains to be seen of the <em>Mediator</em> pattern would be the colleagues that implement this interface. In this case, they receive the mediator dependency through the constructor, and it is stored in a private attribute of the mediator type. This reference is very useful for communicating with the mediator when an event occurs, this is done in the action method, where we can see how it is being notified that an action has been performed that we want to be managed by the mediator through the notify method. This method is sent as a parameter the class itself that sends the request and the message or parameter that we want to be managed from the mediator.</p><!--kg-card-begin: code--><pre><code class="language-typescript">import { Colleague } from "./colleague";
import { Mediator } from "./mediator";

export class Colleague1 implements Colleague {
    private mediator: Mediator;
  
    setMediator(mediator: Mediator): void {
      this.mediator = mediator;
    }
  
    action(): void {
      this.mediator.notify(this, "Event from Colleague1");
    }
}

export class Colleague2 implements Colleague {
    private mediator: Mediator;
  
    setMediator(mediator: Mediator): void {
      this.mediator = mediator;
    }
  
    action(): void {
      this.mediator.notify(this, "Event from Colleague2");
    }
}</code></pre><!--kg-card-end: code--><p>At this point, we can think that the mediator pattern could use another pattern to communicate both to colleagues and to the mediator in a more reactive way, and this would be using the <a href="https://betterprogramming.pub/understanding-the-observer-design-pattern-f621b1d0b6c9">Observer pattern</a>, which we have already talked about in other articles and you can read here. We leave you as a task, once you have internalized the mediator pattern, how to apply the observer pattern together with it.</p><p>To conclude, we would have to see how this pattern is used from the client class.</p><!--kg-card-begin: code--><pre><code class="language-typescript">import { Colleague1 } from "./colleague1";
import { Colleague2 } from "./colleague2";
import { ConcreteMediator } from "./concrete-mediator";

const colleague1 = new Colleague1();
const colleague2 = new Colleague2();

const mediator = new ConcreteMediator(colleague1, colleague2);

colleague1.setMediator(mediator);
colleague2.setMediator(mediator);

colleague1.action();
colleague2.action();</code></pre><!--kg-card-end: code--><p>In this class, the colleagues that interact with each other are instantiated. We relate the colleagues through the mediator, which is the one that will perform the mediation tasks between them.</p><p>On the other hand, we pass the mediator as a parameter to each colleague so that communication between the colleagues and the mediator can be achieved, that is, that the colleagues notify or warn that an event has occurred to the mediator.</p><p>And finally, each colleague will independently execute its action, which will be notified to the mediator and it will perform the different mediation tasks.</p><p>In this way we have decoupled the different colleagues from knowing each other, allowing new colleagues to be created without the need to know each other.</p><p>Now let’s move on to a different example, where we will start by seeing the lack of use of this pattern and then the solution with the pattern.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="example-2-iot-device-control-system-without-mediator-pattern">Example 2: IoT Device Control System without Mediator Pattern</h2><p>In this example, we will create an IoT device control system where devices communicate directly with each other to coordinate their actions. Without the <em>Mediator</em> pattern, the code could be very coupled since devices communicate directly with each other.</p><p>If we look at the UML class diagram, we first find the abstract class <code>IoTDevice</code> that defines the methods that all IoT devices must have. In our case, all devices will have an attribute that corresponds to the <code>id</code>, and then methods to communicate with other devices such as sending and receiving messages. On the other hand, we see that the classes that extend this abstract class implement the methods that are defined for both sensors and actuators. However, to have some difference, we have included the <code>receiveControlSignal</code> method in the <code>Actuator</code> class as an extension of it.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/1000/0*IpJ98aKh7Lp2mBSP" class="kg-image" alt="Understanding the Mediator Design Pattern"></figure><!--kg-card-end: image--><p>It is important to note that devices communicate with other devices through the arguments of the methods they implement, which is where the reference to the colleagues they want to interact with is being sent.</p><p>Finally, we will have the application client class that will make use of all the devices with which it wants to interact.</p><p>Let’s see the implementation of this first solution that does <strong>NOT</strong> use the <em>Mediator</em> pattern.</p><p>The first step is to define the abstract class <code>IoTDevice</code>. This class defines the common methods for all devices, the <code>sendMessage</code> and <code>receiveMessage</code> methods that simply display the information they receive on the screen. Right here, we could have a very different logic but we have simplified it to show how the devices communicate with each other. On the other hand, the <code>sendMeasurement</code> method has some logic in that it can only operate if the receiver is an <code>Actuator</code>, and the specific business logic is implemented there.</p><!--kg-card-begin: code--><pre><code class="language-typescript">abstract class IoTDevice {
    constructor(public id: string) {}
  
    // Method to send a message to another device
    sendMessage(receiver: IoTDevice, message: string): void {
      console.log(`[${this.id}] Sending message to ${receiver.id}: ${message}`);
      // Logic to send the message to the receiver
      receiver.receiveMessage(this, message);
    }
  
    // Method to receive a message from another device
    receiveMessage(sender: IoTDevice, message: string): void {
      console.log(`[${this.id}] Message received from ${sender.id}: ${message}`);
      // Logic to process the received message
    }
      
    // Method to send measurement data to another device
    sendMeasurement(receiver: IoTDevice, data: any): void {
      console.log(`[${this.id}] Sending measurement data to ${receiver.id}: ${JSON.stringify(data)}`);
      // Logic to send the data to the receiver
      if (!(receiver instanceof Actuator)) {
        return console.log("Error: Measurement data can only be sent to an Actuator.");
      } 
      receiver.receiveMeasurement(this, data);
    }

      
    // Method to receive measurement data from a sensor
    receiveMeasurement(sender: IoTDevice, data: any): void {
      console.log(`[${this.id}] Measurement data received from ${sender.id}: ${JSON.stringify(data)}`);
      // Logic to process the received measurement data
    }
}</code></pre><!--kg-card-end: code--><p>The concrete classes that extend the abstract class would be the colleagues of the pattern. Specifically, we would have two types of devices: sensors and actuators.</p><!--kg-card-begin: code--><pre><code class="language-typescript">export class Sensor extends IoTDevice {
    constructor(id: string) {
      super(id);
    }
}
  
export class Actuator extends IoTDevice {
    constructor(id: string) {
      super(id);
    }
    // Method to receive a control signal from another device
    receiveControlSignal(sender: IoTDevice, signal: string): void {
       console.log(`[${this.id}] Receiving control signal from ${sender.id}: ${signal}`);
       // Logic to process the received control signal
   }
}</code></pre><!--kg-card-end: code--><p>We can see how these classes extend the abstract class. On the one hand, the <code>Sensor</code> class, which does not have any extra particularity and therefore is still without extended methods, and on the other hand the <code>Actuator</code> class, which has its own method, which we implement in its concrete class.</p><p>Finally, we would have to see the code of the client that makes use of all these classes. The first thing we have to do is create all the devices. To do this, we create two sensors and one actuator. These are our colleagues who want to interact with each other.</p><!--kg-card-begin: code--><pre><code class="language-typescript">const sensor1 = new Sensor("Sensor1");
const sensor2 = new Sensor("Sensor2");
const actuator1 = new Actuator("Actuator1");
  
// Example interaction between devices
sensor1.sendMessage(sensor2, "How are you?");
sensor2.sendMeasurement(actuator1, { temperature: 25, humidity: 60 });
actuator1.receiveControlSignal(sensor2, "Turn off");</code></pre><!--kg-card-end: code--><p>And then we see the communication between them, how first <code>sensor1</code> has to send <code>sensor2</code> as an argument to send it a message. On the other hand, <code>sensor2</code>s has to send <code>actuator1</code>a and the configuration parameters as arguments so that it receives them.</p><p>Finally, the <code>actuator</code> has to send <code>sensor2</code> and the information as arguments.<strong> </strong>Here, the coupling between the different colleagues is clearly visible, since they are going to talk to each other directly from their implementations, in this case in the <code>IoTDevice</code> abstract class, which is the one that manages all the work to be done.</p><p>Let’s move on to decoupling this code right now.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="example-2-iot-device-control-system-using-mediator-pattern">Example 2: IoT Device Control System Using Mediator Pattern</h2><p>The problems that appear in the solution without the <em>Mediator</em> pattern are the following:</p><ul><li><strong>High Cohesion:</strong> The communication logic is coupled between objects and any change in the logic affects different classes.</li><li><strong>Scalability and maintainability:</strong> Adding new objects implies modifying other classes to fit. In addition, there is greater difficulty in understanding and modifying the communication flow between objects.</li><li><strong>Tight coupling:</strong> There is a strong dependency between the objects involved in the communication, which makes it difficult to modify or reuse them independently.</li></ul><p>Therefore, in this example, we clearly see the need for the <em>Mediator</em> pattern, where we could include an element that would be the connection point between the different colleagues.</p><p>Let’s start by seeing how the UML class diagram evolves.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/1000/0*6-or9hk5HV6Q7Wgk" class="kg-image" alt="Understanding the Mediator Design Pattern"></figure><!--kg-card-end: image--><p>We start by seeing that the abstract class has not changed in the definition of the methods that are defined in it a priori<strong>.</strong> But there is a very important change, now the devices do not communicate with other devices, but rather a request is made about which device you want to communicate with, this parameter could be a unique identifier to find it, in our case to simplify we are going to use a string to define the device <code>id</code>.</p><p>This subtle but very important change. In addition, we now find that we will have an attribute called <code>mediator</code> which will be responsible for performing the tasks where the devices interact with each other. Finally, the definition of the <code>Sensor</code> and <code>Actuator</code> classes now we have to reference this <code>mediator</code> attribute through the constructor of the classes. We could have assigned the mediator through the constructor or with a <code>setMediator</code> accessor method, that is already up to the developer.</p><p>On the other hand of the class diagram we can see that we have an interface called <code>IoTMediator</code> that specifies the necessary methods that all concrete mediators must implement. In our example we will only have one concrete mediator that we have called <code>ConcreteMediatorIoT</code>. This concrete mediator is responsible for coordinating the different devices.</p><p>Well, let’s go step by step, the implementation and how it has changed compared to the previous example to achieve decouple the communication between the different devices.</p><p>Let’s start with the code of the abstract class <code>IoTDevice</code> which models the common logic of all devices.</p><!--kg-card-begin: code--><pre><code class="language-typescript">import { IoTMediator } from "./iot-mediator";

export abstract class IoTDevice {
    constructor(public id: string, protected mediator: IoTMediator) {
      mediator.registerDevice(this);
    }
  
    // Method to send a message to another device
    sendMessage(receiverId: string, message: string): void {
      this.mediator.sendMessage(this, receiverId, message);
    }
  
    // Method to send measurement data to another device
    sendMeasurement(receiverId: string, data: any): void {
      this.mediator.sendMeasurement(this, receiverId, data);
    }
  
    // Method to receive a message from another device
    receiveMessage(senderId: string, message: string): void {
      this.mediator.receiveMessage(this, senderId, message);
    }
  
    // Method to receive measurement data from another device
    receiveMeasurement(senderId: string, data: any): void {
      this.mediator.receiveMeasurement(this, senderId, data);
        // Logic to process the received measurement data
   }
}</code></pre><!--kg-card-end: code--><p>If we look at the constructor we see that we create a new device from its identifier and a mediator. When the device is instantiated, what is done is to register the device with the mediator. This is done through the <code>registerDevice</code> method which receives as an argument the instance of the <code>Device</code> class that has just been created, important, this method will be executed in the concrete device classes, that is, in the <code>Sensor</code> or <code>Actuator</code> class. In our case, we have merged in the constructor methods that could have been divided into methods such as the accessor method that would register the concrete mediator to the device, and another later that would register the device with the mediator. However, to simplify the code since the objective of the pattern is another, we have simplified it into a single method.</p><p>The rest of the common methods that all devices have are very simple, since we are delegating the responsibility to the mediator, through concrete mediator methods. The mediator only needs to know which device wants to perform the operation, it does this through the first argument with the reserved word this, and then the specific parameters of the operation that you want to perform. It is important to note that the interaction logic between colleagues has been delegated to the mediator.</p><p>The next thing is to see the specific devices, the <code>Sensor</code> class does not have anything extra since we have simplified it as much as possible and does not have any extra behavior. So we can see that the constructor simply invokes the class it extends.</p><!--kg-card-begin: code--><pre><code class="language-typescript">import { IoTDevice } from "./iot-device";
import { IoTMediator } from "./iot-mediator";

export class Sensor extends IoTDevice {
    constructor(id: string, mediator: IoTMediator) {
      super(id, mediator);
    }
}</code></pre><!--kg-card-end: code--><p>On the other hand, the <code>Actuator</code>  class includes an extra method to the base class, which is <code>receiveControlSignal</code>, but if we look closely, we are doing exactly the same, we are delegating the communication responsibility to the mediator class which is responsible for putting the devices in contact.</p><!--kg-card-begin: code--><pre><code class="language-typescript">import { IoTDevice } from "./iot-device";
import { IoTMediator } from "./iot-mediator";

export class Actuator extends IoTDevice {
    constructor(id: string, mediator: IoTMediator) {
      super(id, mediator);
    }
  
    // Method to receive a control signal from another device
    receiveControlSignal(senderId: string, signal: string): void {
      this.mediator.receiveControlSignal(this, senderId, signal);
    }
}</code></pre><!--kg-card-end: code--><p>Now let’s see the concrete part of the pattern, the part corresponding to the mediators.</p><p>Let’s start by seeing the <code>IoTMediator</code> interface where you can see all the methods that the different colleagues use. To simplify we have included the method that we would only have in the <code>Actuator</code>. If we wanted to do it even better, instead of having a single concrete mediator, we could have two concrete mediators, one for the sensors and one for the actuators. However, we say the same again, we want to get the idea of how the mediator pattern works, once we have it, we can apply other different techniques or other patterns that allow us to continue decoupling the different parts of the code.</p><!--kg-card-begin: code--><pre><code class="language-typescript">import { IoTDevice } from "./iot-device";

export interface IoTMediator {
    registerDevice(device: IoTDevice): void;
    sendMessage(sender: IoTDevice, receiverId: string, message: string): void;
    sendMeasurement(sender: IoTDevice, receiverId: string, data: any): void;
    receiveMessage(receiver: IoTDevice, senderId: string, message: string): void;
    receiveMeasurement(receiver: IoTDevice, senderId: string, data: any): void;
    receiveControlSignal(receiver: IoTDevice, senderId: string, signal: string): void;
}</code></pre><!--kg-card-end: code--><p>The business logic of communication between the different devices is in the <code>ConcreteIoTMediator</code> class. In this class we have a <code>Map</code> of devices as an attribute. In this way, we have all the devices that want to interact with each other. To add devices to this data structure, we have designed the <code>registerDevice</code> method, which receives any device, both sensors and actuators, and is added to the <code>Map</code>.</p><p>We have prepared a private <code>findOrError</code> method that will search the <code>Map</code> for the device if it exists based on a device <code>id</code> and return it or if it does not exist, we will return an error that the device is not registered.</p><p>And now if we look at the <code>sendMessage</code> method, here we can see how the mediator is the one that coordinates the devices. The first thing that is done is to retrieve the receiver that is going to receive the message, and we can see how we invoke the <code>receiveMessage</code> method of the receiver once the message has been received from the sender. This device method will return to the mediator, and it will be the <code>receiveMessage</code> method that we have implemented in this class. The <code>receiveMessage</code> method is quite simple since it only performs a result trace to verify that all the communication between these devices is correct.</p><p>On the other hand, we see the <code>sendMeasurement</code> method which includes some logic, in which we explicitly check that the receiver must be of the <code>Actuator</code> class, otherwise, we return an error.</p><!--kg-card-begin: code--><pre><code class="language-typescript">import { Actuator } from "./actuator";
import { IoTDevice } from "./iot-device";
import { IoTMediator } from "./iot-mediator";

export class ConcreteIoTMediator implements IoTMediator {
    private devices: Map&lt;string, IoTDevice&gt; = new Map();
  
    registerDevice(device: IoTDevice): void {
      this.devices.set(device.id, device);
    }

    private findOrError(id: string): IoTDevice {
      const device = this.devices.get(id);
      if (!device) {
        throw new Error(`Device ${id} not found.`);
      }
      return device;
    }
  
    sendMessage(sender: IoTDevice, receiverId: string, message: string): void {
      const receiver = this.findOrError(receiverId);

      console.log(`[${sender.id}] Sending message to ${receiverId}: ${message}`);
      receiver.receiveMessage(sender.id, message);   
    }
  
    sendMeasurement(sender: IoTDevice, receiverId: string, data: any): void {
      const receiver = this.findOrError(receiverId);
 
      console.log(`[${sender.id}] Sending measurement data to ${receiverId}: ${JSON.stringify(data)}`);
      // Logic to send the data to the receiver
      if (!(receiver instanceof Actuator)) {
        return console.log("Error: Measurement data can only be sent to an Actuator.");
      } 
      receiver.receiveMeasurement(sender.id, data);
    }

    receiveMessage(receiver: IoTDevice, senderId: string, message: string): void {
      const sender = this.findOrError(senderId);

      console.log(`[${receiver.id}] Message received from ${sender.id}: ${message}`);
      // Logic to process the received message
    }

    receiveMeasurement(receiver: IoTDevice, senderId: string, data: any): void {
      const sender = this.findOrError(senderId);
      console.log(`[${receiver.id}] Measurement received from ${sender.id}: ${JSON.stringify(data)}`);
      // Logic to process the received message
    }

    receiveControlSignal(receiver: IoTDevice, senderId: string, signal: string): void {
      const sender = this.findOrError(senderId);
  
      console.log(`[${receiver.id}] Receiving control signal from ${sender.id}: ${signal}`);
        // Logic to process the received control signal
  }
}</code></pre><!--kg-card-end: code--><p>In this way, the mediators are the ones that implement the communication between the devices, or colleagues, and of course, we have to be careful not to make the mediators into <em>God classes</em>, since this would be an anti-pattern that we have to fix in a next phase of software development.</p><p>The client that makes use of the pattern, we must have a first phase of instantiation of all the necessary classes, mediator and different devices. Then each device makes use of its communication interface. For example, <code>sensor1</code> uses the <code>sendMessage</code> method, or <code>sensor2</code> the <code>sendMeasurement</code> method. Important, now the devices are not communicating directly, but an identifier is being specified with which to communicate.</p><!--kg-card-begin: code--><pre><code class="language-typescript">import { Actuator } from "./actuator";
import { ConcreteIoTMediator } from "./concrete-iot-mediator";
import { Sensor } from "./sensor";
// Create the Mediator
const mediator = new ConcreteIoTMediator();

// Create IoT devices
const sensor1 = new Sensor("Sensor1", mediator);
const sensor2 = new Sensor("Sensor2", mediator);
const actuator1 = new Actuator("Actuator1", mediator);

// Example interaction between devices
sensor1.sendMessage("Sensor2", "How are you?");
sensor2.sendMeasurement("Actuator1", { temperature: 25, humidity: 60 });
actuator1.receiveControlSignal("Sensor2", "Turn off");

sensor1.sendMessage("Invalid-sensor", "How are you?");</code></pre><!--kg-card-end: code--><p>And with this, we conclude by seeing the example, and we will see how this pattern is related to other design patterns.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="mediator-pattern-relationship-with-other-patterns"><strong>Mediator Pattern: Relationship with other patterns</strong></h3><p>The <em>Mediator</em> pattern can be related to several other design patterns, as it is often used in conjunction with them to solve complex software design problems. Some of the related patterns include:</p><p><strong>1. </strong><strong><a href="https://carloscaballero.io/understanding-the-observer-design-patterns/">Observer Pattern</a></strong><strong>: </strong>The Observer pattern is often used together with the <em>Mediator</em> pattern to allow objects to subscribe to and receive notifications about changes in other objects. This can help to keep objects loosely coupled and facilitate two-way communication.</p><p><strong>2. </strong><strong><a href="https://carloscaballero.io/design-patterns-singleton/">Singleton Pattern</a></strong><strong>: </strong>A mediator is sometimes implemented as a singleton to ensure that there is only one instance of the mediator in the system. This can be useful to ensure that all objects in the system communicate through the same centralized mediator.</p><p><strong>3. </strong><strong><a href="https://carloscaballero.io/design-patterns-command/">Command Pattern</a></strong><strong>: </strong>The Command pattern can be used together with the <em>Mediator</em> pattern to encapsulate requests as objects, allowing clients to parameterize other objects with requests, rather than sending requests directly. This can make it easier to implement systems with logging and undo capabilities.</p><p><strong>4. </strong><strong><a href="https://carloscaballero.io/understanding-design-patters-factory-method/">Factory Method Pattern</a></strong><strong>: </strong>The Factory Method pattern is often used to create instances of objects that interact through a mediator. This can help to hide the complexity of object creation and ensure that the correct implementations of objects are used in the system.</p><p><strong>5. </strong><a href="https://blog.bitsrc.io/understanding-the-state-design-pattern-7f40f6b5e29e" rel="noopener"><strong>State Pattern</strong></a><strong>: </strong>The State pattern is sometimes used together with the <em>Mediator</em> pattern to allow an object to change its behavior when its internal state changes. The mediator may be responsible for changing the state of an object and notifying other objects about the state change.</p><p>These are just a few examples of patterns that may be related to the <em>Mediator</em> pattern<strong>.</strong> Depending on the context and system requirements, other pattern combinations may emerge to address different design issues.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="conclusions"><strong>Conclusions</strong></h3><p>In general, the <em>Mediator</em> pattern is a valuable tool for designing systems with complex communication between objects, especially when looking for:</p><ul><li><strong>Low coupling:</strong> Collaborating objects do not know each other directly, but communicate through the mediator. This reduces dependencies between objects and makes them easier to reuse and maintain.</li><li><strong>Centralization of communication logic:</strong> The logic of how objects interact is encapsulated in the mediator, making it easier to understand and modify.</li><li><strong>Communication flexibility:</strong> The mediator can be implemented in different ways to adapt to the specific needs of the system.</li><li><strong>Code reuse:</strong> The mediator can be reused in different parts of the system, reducing the amount of duplicate code.</li></ul><p>However, the use of the <em>Mediator</em> pattern also has some disadvantages:</p><ul><li><strong>Increased complexity:</strong> The system design may be more complex, since a new object (the mediator) must be added to manage communication.</li><li><strong>Potential performance loss:</strong> Indirect communication through the mediator may be slightly slower than direct communication between objects.</li></ul><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><p>The most important thing about the <em>Mediator</em> pattern is not its specific implementation, but the ability to recognize the problem that this pattern can solve and when <strong>it can be applied.</strong> The specific implementation is not that important, as it will vary depending on the programming language used.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><p>See this<a href="https://github.com/Caballerog/blog/tree/master/mediator-pattern" rel="noopener"> GitHub repo </a>for the full code.</p><p></p><p></p>]]></content:encoded></item><item><title><![CDATA[Understanding the Bridge Design Pattern]]></title><description><![CDATA[<p>There are 23 classic design patterns described in the original book <a href="https://amzn.to/3VN3Ygd">Design Patterns: Elements of Reusable Object-Oriented Software</a>. These patterns provide solutions to particular problems often repeated in software development.</p><p>In this article, I am going to describe how the <em>Bridge</em> pattern works and when it should be applied.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="bridge-basic-idea"><strong>Bridge:</strong></h3>]]></description><link>https://www.carloscaballero.io/understanding-the-bridge-design-pattern/</link><guid isPermaLink="false">663de6949c7a350001e7e253</guid><category><![CDATA[NodeJS]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Carlos Caballero]]></dc:creator><pubDate>Fri, 10 May 2024 09:36:47 GMT</pubDate><media:content url="http://www.carloscaballero.io/content/images/2024/05/1_p-gHXh95WZjHzdVetmLZnQ.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://www.carloscaballero.io/content/images/2024/05/1_p-gHXh95WZjHzdVetmLZnQ.jpg" alt="Understanding the Bridge Design Pattern"><p>There are 23 classic design patterns described in the original book <a href="https://amzn.to/3VN3Ygd">Design Patterns: Elements of Reusable Object-Oriented Software</a>. These patterns provide solutions to particular problems often repeated in software development.</p><p>In this article, I am going to describe how the <em>Bridge</em> pattern works and when it should be applied.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="bridge-basic-idea"><strong>Bridge: Basic Idea</strong></h3><p>According to <a href="https://en.wikipedia.org/wiki/Bridge_pattern">Wikipedia</a>, the <em>Bridge</em> pattern is a structural software design pattern that separates an abstraction from its implementation, so that both can vary independently. This pattern promotes composition over inheritance by decoupling the abstraction from its implementation. The main idea is to have two independent class hierarchies, one for the abstraction and another for the implementation, and then connect them together using a bridge.</p><p>On the other hand, the definition provided by the original book is as follows:</p><p>Separate an abstraction from its implementation so that both can vary independently.</p><p>In many cases, we encounter situations where we want the flexibility to change both the abstraction and the implementation of an object independently. For example, in a drawing system, we may have different shapes (<em>abstractions</em>) that can be drawn in different ways (implementations). This is where the <em>Bridge</em> design pattern can help us write more flexible and maintainable code.</p><p>Next, let’s take a look at the UML class diagram of this pattern to understand each of the elements that interact in it.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/1000/1*0tK4s0xheAKiQclzVHlJXA.png" class="kg-image" alt="Understanding the Bridge Design Pattern"></figure><!--kg-card-end: image--><p>These are the classes that comprise this pattern:</p><ul><li><strong>Abstraction:</strong> This is the interface of interest to clients. It maintains a reference to an <code>Implementor</code> object that defines the abstract interface for the implementation classes.</li><li><strong>RefinedAbstraction:</strong> This class extends the interface defined by <code>Abstraction</code>. It can add additional methods or functionality specific to the abstraction.</li><li><strong>Implementor:</strong> This defines the interface for the implementation classes. It does not have to correspond directly to <code>Abstraction’s</code> interface.</li><li><strong>ConcreteImplementorA</strong> and <strong>ConcreteImplementorB:</strong> These are the subclasses that implement the <code>Implementor</code> interface. Each <code>ConcreteImplementor</code> provides a specific implementation of the interface defined by <code>Implementor</code>.</li></ul><p>By separating the abstraction from its implementation and allowing them to vary independently, the <em>Bridge</em> pattern enables greater flexibility and extensibility in our codebase.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="bridge-pattern-when-to-use-it"><strong>Bridge Pattern: When to Use It</strong></h3><p>The Bridge design pattern is particularly useful in the following scenarios:</p><ol><li><strong>You want to separate an abstraction from its implementation</strong>: The <em>Bridge</em> pattern is ideal when you need to have the flexibility to vary both the abstraction and the implementation independently. By decoupling these two aspects, you can make changes to one without affecting the other.</li><li><strong>You have multiple hierarchies that need to be extended independently</strong>: When you have two or more orthogonal class hierarchies that need to be extended independently, the <em>Bridge</em> pattern provides an elegant solution. It allows you to manage each hierarchy separately and then connect them as needed through the bridge.</li><li><strong>You want to avoid a proliferation of subclasses</strong>: Without the <em>Bridge</em> pattern, you might end up with a large number of subclasses, each combining different abstractions with different implementations. This can lead to a complex and rigid class hierarchy. By using the <em>Bridge</em> pattern, you can avoid this proliferation of subclasses and keep your codebase more manageable.</li></ol><p>In summary, the <em>Bridge</em> pattern is beneficial when you need to decouple abstraction from implementation, manage multiple hierarchies independently, and avoid a proliferation of subclasses.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="bridge-pattern-advantages-and-disadvantages"><strong>Bridge Pattern: Advantages and Disadvantages</strong></h3><p>The <em>Bridge</em> pattern offers several advantages, which can be summarized as follows:</p><h4 id="advantages"><strong>Advantages</strong></h4><ol><li><strong>Decoupling of abstraction and implementation</strong>: The <em>Bridge</em> pattern promotes decoupling by separating an abstraction from its implementation. This allows changes to one side of the bridge to occur without affecting the other side, thus enhancing flexibility and maintainability.</li><li><strong>Enhanced extensibility</strong>: By allowing both the abstraction and implementation to vary independently, the <em>Bridge</em> pattern facilitates easier extension of the system. New abstractions or implementations can be introduced without requiring modifications to existing code, thereby adhering to the <em>Open-Closed Principle</em>.</li><li><strong>Reduced Class Proliferation</strong>: The <em>Bridge</em> pattern helps prevent class explosion by avoiding the creation of a large number of subclasses to handle different combinations of abstractions and implementations. Instead, it promotes a more modular and manageable class structure.</li></ol><p>However, like most design patterns, the <em>Bridge</em> pattern also comes with its drawbacks.</p><h4 id="disadvantages">Disadvantages</h4><ol><li><strong>Increased complexity</strong>: Implementing the <em>Bridge</em> pattern may introduce additional complexity to the codebase, as it involves defining multiple interfaces and classes to manage the separation between abstraction and implementation.</li><li><strong>Higher initial overhead</strong>: Initially, applying the <em>Bridge</em> pattern may require more effort to set up the necessary abstractions, implementations, and bridges. This upfront cost may deter developers from using the pattern in simpler scenarios.</li></ol><p>In summary, while the <em>Bridge</em> pattern offers advantages such as decoupling and extensibility, it also requires careful consideration of the trade-offs, particularly regarding code complexity and initial overhead.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="bridge-pattern-examples"><strong>Bridge Pattern Examples</strong></h3><p>Next, we will illustrate the <em>Bridge</em> pattern with two examples:</p><ol><li><strong>Basic Structure of the Bridge Pattern</strong>: In this example, we will translate the theoretical UML diagram into <strong>TypeScript</strong> code to identify each of the classes involved in the pattern.</li><li><strong>Multiplatform Messaging System</strong>: Let’s consider a messaging system that needs to function on both mobile devices and desktop computers. Without the <em>Bridge</em> pattern, the code could become tightly coupled to specific platforms, requiring significant code rewriting whenever a platform change is needed. We will first demonstrate the code without applying the <em>Bridge</em> pattern, and then we will show how applying the pattern can help decouple the code from platform-specific implementations.</li></ol><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="example-1-basic-structure-of-the-bridge-pattern">Example 1: Basic Structure of the Bridge Pattern</h3><p>First of all, we can see the UML class diagram of the implementation using the <em>Bridge</em> design pattern.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/1000/1*0sJunzCjmdPqBqBgQ-XIWA.png" class="kg-image" alt="Understanding the Bridge Design Pattern"></figure><!--kg-card-end: image--><p>So let’s start looking at its implementation in code. The first element of this design pattern is the <code>Implementor</code> interface, where the different operations that we want all concrete implementations to have are defined.</p><!--kg-card-begin: code--><pre><code>export interface Implementor {
	operationImplementation(): void;
 }</code></pre><!--kg-card-end: code--><p>The next step would be to see the concrete classes that satisfy the concrete interface; in our example, we are only defining a single method for our classes. This first branch focuses on the concrete implementations, not on the abstractions.</p><!--kg-card-begin: code--><pre><code>import { Implementor } from './implementor';

export class ConcreteImplementorA implements Implementor {
    operationImplementation(): void {
        console.log("ConcreteImplementorA operation implementation.");
    }
}

export class ConcreteImplementorB implements Implementor {
    operationImplementation(): void {
        console.log("ConcreteImplementorB operation implementation.");
    }
}
</code></pre><!--kg-card-end: code--><p>The second part of the UML class diagram shows the part corresponding to the abstractions. The <code>Abstraction</code> class is an abstract class and therefore cannot be instantiated, but the key here is that it has an attribute that must adhere to the <code>Implementor</code> interface. In this case, we have achieved composition through the constructor of the <code>Abstraction</code> class; of course, we could have done it through an accessor method. The other key point of this abstraction class is that there is an abstract method, in our case operation, which will be implemented in a class that extends this abstract class.</p><!--kg-card-begin: code--><pre><code>import { Implementor } from './implementor';

export abstract class Abstraction {
    protected implementor: Implementor;

    constructor(implementor: Implementor) {
        this.implementor = implementor;
    }

    abstract operation(): void;
}
</code></pre><!--kg-card-end: code--><p>If we take a look at the last class of the <em>refine abstraction</em> design pattern, we see that it extends the abstraction class, and there we have the concrete implementation of the operation method, which uses an instance of a class that satisfies the <code>Implementor</code> interface, which could be either <code>concreteImplementorA</code> or <code>concreteImplementorB</code>.</p><!--kg-card-begin: code--><pre><code>import { Abstraction } from './abstraction';

export class RefinedAbstraction extends Abstraction {
    operation(): void {
        console.log('RefinedAbstraction: operation');
        this.implementor.operationImplementation();
    }
}
</code></pre><!--kg-card-end: code--><p>Finally, let’s take a look at the class that utilizes the <em>bridge</em> pattern.</p><p>The <code>client</code> class instantiates both <code>concreteImplementor</code> classes, which are then used to create an instance of the <code>refineAbstraction</code> class, with the desired <code>concreteImplementor</code> passed as a parameter. Ultimately, it is the abstraction class that invokes the refined abstraction.</p><!--kg-card-begin: code--><pre><code>import { Abstraction } from './abstraction';
import { ConcreteImplementorA } from './concrete-implementorA';
import { ConcreteImplementorB } from './concrete-implementorB';
import { RefinedAbstraction } from './refine-abstraction';

class Client {
    static main(): void {
        const implementorA = new ConcreteImplementorA();
        const implementorB = new ConcreteImplementorB();

        let abstraction: Abstraction = new RefinedAbstraction(implementorA);
        abstraction.operation();

        abstraction = new RefinedAbstraction(implementorB);
        abstraction.operation();
    }
}
Client.main();
</code></pre><!--kg-card-end: code--><p>In this way, we have decoupled the implementation from the abstraction.</p><p>If anyone has noticed that the structure of this design pattern resembles surprisingly the <em>template-method</em> and <em>strategy</em> patterns, we will leave a comparison of these three patterns at the end of the post. Now let’s move on to a different example, where we will start by observing the lack of use of this pattern and then the solution with the pattern.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="example-2-multiplatform-messaging-system-problem">Example 2: Multiplatform Messaging System — Problem</h3><p>Let’s think about a messaging system that needs to work on both mobile and desktop devices. Without the <em>Bridge</em> pattern, the code could be tightly coupled to specific platforms, making any changes to the platform require significant code rewriting.</p><p>If we look at the UML class diagram, we find two different classes that have two different implementations for each messaging system. On one side, we have the <code>MobileMessaging</code> class, and on the other side, <code>DesktopMessaging</code>. Both classes implement methods for sending and receiving messages. In the case of the <code>DesktopMessaging</code> class, the methods are named <code>sendMessageFromDesktop</code> and <code>receiveMessageOnDesktop</code>, while for the <code>MobileMessaging</code> class, the methods are named <code>sendMessageFromMobile</code> and <code>receiveMessageOnMobile</code>.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/1000/1*aNcpXkwTCFlktenarFN8HQ.png" class="kg-image" alt="Understanding the Bridge Design Pattern"></figure><!--kg-card-end: image--><!--kg-card-begin: code--><pre><code>export class DesktopMessaging {
    sendMessageFromDesktop(message: string): void {
        console.log("Sending message from a desktop: " + message);
    }

    receiveMessageOnDesktop(): string {
        return "Message received on a desktop.";
    }
}

export class MobileMessaging {
    sendMessageFromMobile(message: string): void {
        console.log("Sending message from a mobile device: " + message);
    }

    receiveMessageOnMobile(): string {
        return "Message received on a mobile device.";
    }
}
</code></pre><!--kg-card-end: code--><p>On the other hand, we have a client that directly uses both classes, instantiating them and causing direct coupling to these two classes. If there is any change in them now, we don’t have a common interface acting as a contract between the classes, leading to direct coupling. Let’s see the implementation.</p><p>The code for these classes is quite simple, as we can see. Both classes have the two methods that either display a message via <code>console.log</code> or return a string, nothing more.</p><!--kg-card-begin: code--><pre><code>import { DesktopMessaging } from "./desktop-messaging";
import { MobileMessaging } from "./mobile-messaging";

class Client {
    static main(): void {
        const mobileMessaging = new MobileMessaging();
        mobileMessaging.sendMessageFromMobile("Hello from Mobile!");
        console.log(mobileMessaging.receiveMessageOnMobile());

        const desktopMessaging = new DesktopMessaging();
        desktopMessaging.sendMessageFromDesktop("Hello from Desktop!");
        console.log(desktopMessaging.receiveMessageOnDesktop());
    }
}

Client.main();
</code></pre><!--kg-card-end: code--><p>In the <code>Client</code> class, we can see how we have to instantiate two different objects of the <code>MobileMessaging</code> and <code>DesktopMessaging</code> classes. Then, we use the methods specific to each of these classes. In one case, <code>sendMessageFromMobile</code>, and in the other, <code>sendMessageFromDesktop</code>. Here, we detect, on one hand, the lack of a common interface that could unify these methods, but also, we notice that if there is a change in these methods, the code is tightly coupled, and the client must be completely redefined. Furthermore, the example also ends up using the <code>receiveMessageOnMobile</code> and <code>receiveMessageOnDesktop</code> methods, which have the same problem as the previous methods. Additionally, in case the classes are extended through inherited classes, we will encounter an explosion of unnecessary classes.</p><p>Next, we will see the solution using the <em>Bridge</em> design pattern.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="example-2-multiplatform-messaging-system-solution">Example 2: Multiplatform Messaging System — Solution</h3><p>As we’ve discussed, the problems that arise in this solution without the <em>Bridge</em> design pattern are as follows:</p><ol><li><strong>Code duplication</strong>: Each class has very similar methods, leading to code duplication.</li><li><strong>High cohesion</strong>: The messaging logic is tightly coupled to the specific platform, making it difficult to make changes to the messaging logic without affecting the specific platform implementation.</li><li><strong>Scalability and maintainability</strong>: Adding support for new platforms or changing messaging behavior requires extensive modifications or code duplication.</li></ol><p>In this example, we clearly see the need for the <em>Bridge</em> pattern, where we can separate the abstraction meaning the messaging operations, from its implementation which would be the specific platform details, allowing both to vary independently. In the next step, let’s refactor this code to implement the <em>Bridge</em> pattern and address these issues.</p><p>Let’s start by looking at how the UML class diagram evolves.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/1000/1*I_9gU4yBMGbkmf5DTTU0pg.png" class="kg-image" alt="Understanding the Bridge Design Pattern"></figure><!--kg-card-end: image--><p>First, we see in the diagram the <code>MessageSender</code> interface that we needed in the code without the pattern. This interface defines the methods <code>sendMessage</code> and <code>receiveMessage</code>. This interface is common to all concrete classes.</p><p>In this case, the concrete implementations for the desktop and mobile platforms are implemented in the <code>DesktopSender</code> and <code>MobileSender</code> classes. We have the concrete implementations on this side, and now we need to see the abstractions.</p><p>If we look at the <code>MessagingService</code> class, it is an abstract class that includes an object that satisfies the <code>MessageSender</code> interface, which can be either desktop or mobile, or even if there were a new platform like <code>XBOXSender</code>, it would still work as long as it adheres to the <code>MessageSender</code> interface. Because this is an abstract class, we need to have a class that extends it and implements the abstract methods of this class, namely, the send and receive methods.</p><p>The <code>AdvancedMessaging</code> class is responsible for implementing the <code>send</code> and <code>receive</code> methods. Of course, in our case, it will make use of the sender instance. Finally, the client will only use the <code>AdvancedMessaging</code> class and the specific platform it needs. Let’s see this solution through the source code.</p><p>Let’s see this solution through the source code.</p><!--kg-card-begin: code--><pre><code>export interface MessageSender {
    sendMessage(message: string): void;
    receiveMessage(): string;
}</code></pre><!--kg-card-end: code--><p>Let’s start by looking at the <code>MessageSender</code> interface, which simply defines the two operations we want to perform, <code>sendMessage</code> and <code>receiveMessage</code>.</p><!--kg-card-begin: code--><pre><code>import { MessageSender } from './message-sender';

export class DesktopSender implements MessageSender {
    sendMessage(message: string): void {
        console.log("Sending message from a desktop: " + message);
    }

    receiveMessage(): string {
        return "Message received on a desktop.";
    }
}</code></pre><!--kg-card-end: code--><!--kg-card-begin: code--><pre><code>import { MessageSender } from './message-sender';

export class MobileSender implements MessageSender {
    sendMessage(message: string): void {
        console.log("Sending message from a mobile device: " + message);
    }

    receiveMessage(): string {
        return "Message received on a mobile device.";
    }
}</code></pre><!--kg-card-end: code--><p>In this case, the codes are identical to those we had in the solution without the pattern. In fact, this is because these are the concrete implementations we had in the solution without the pattern. Therefore, here we have simply created a common interface for both classes. This simple change could have been made without having the <em>bridge</em> pattern, and we would already have gained in decoupling our first solution. However, what the <em>bridge</em> pattern will allow us to do is to grow in the concrete implementations on the one hand and the abstractions on the other.</p><p>The abstract <code>MessagingService</code> class has an attribute that satisfies the <code>MessageSender</code> interface. In this case, we include it through the constructor but we could do it from an accessor method.</p><p>The key is that we define the methods that we want the abstractions to have, in our case the send and receive methods that will be implemented in the hierarchy of abstraction classes.</p><!--kg-card-begin: code--><pre><code>import { MessageSender } from './message-sender';

export abstract class MessagingService {
    protected sender: MessageSender;

    constructor(sender: MessageSender) {
        this.sender = sender;
    }

    abstract send(message: string): void;
    abstract receive(): string;
}</code></pre><!--kg-card-end: code--><p>In the following concrete implementation of the previous abstraction, we extend the <code>MessagingService</code> class and therefore, we already have the sender attribute thanks to the parent class. Now, we make the concrete implementation of the <code>send</code> and <code>receive</code> methods, where in both cases we are making use of the methods of the instance of the sender attribute, delegating the responsibility to this instance.</p><!--kg-card-begin: code--><pre><code>import { MessagingService } from './messaging-sender';

export class AdvancedMessaging extends MessagingService {
    send(message: string): void {
        this.sender.sendMessage(message);
    }

    receive(): string {
        return this.sender.receiveMessage();
    }
}
</code></pre><!--kg-card-end: code--><p>If we look at the final code, we can see that when we are creating the platform to send mobile messages, we will create an instance of the <code>AdvancedMessaging</code> abstraction by receiving an object of the <code>MobileSender</code> instance. On the other hand, if it were to send desktop messages, it would be exactly the same but instead of passing a <code>MobileSender</code> instance as an argument, it would be a <code>DesktopSender</code> instance. Later, on both platforms we will use the methods that we have in the interface, the send methods to send messages and the receive method to receive them.</p><!--kg-card-begin: code--><pre><code>import { AdvancedMessaging } from "./advanced-messaging";
import { DesktopSender } from "./desktop-sender";
import { MobileSender } from "./mobile-sender";

class Client {
    static main(): void {
        // Use mobile sender
        const mobileMessaging = new AdvancedMessaging(new MobileSender());
        mobileMessaging.send("Hello from Mobile!");
        console.log(mobileMessaging.receive());

        // Use desktop sender
        const desktopMessaging = new AdvancedMessaging(new DesktopSender());
        desktopMessaging.send("Hello from Desktop!");
        console.log(desktopMessaging.receive());
    }
}

Client.main();</code></pre><!--kg-card-end: code--><p>This design using the <em>bridge</em> pattern allows you to easily change the message sending implementation without modifying the rest of the client code or the messaging application logic. Each component can be developed, tested, and maintained independently.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="differences-between-bridge-strategy-and-template-method">Differences between Bridge, Strategy, and Template Method</h3><p>Although the <em>Bridge</em>, <em>Strategy</em>, and <em>Template Method</em> patterns share certain similarities, each one has a different purpose and structure. Here’s a description of the key differences between them:</p><h4 id="bridge-pattern-">Bridge Pattern:</h4><ul><li><strong>Purpose</strong>: The <em>Bridge</em> pattern focuses on separating an abstraction from its implementation so that both can vary independently.</li><li><strong>Structure</strong>: It typically involves defining an abstraction hierarchy and an implementation hierarchy, with a bridge connecting the two hierarchies.</li><li><strong>Use Cases</strong>: It is useful when there is a need to support multiple implementations of an abstraction, or when changes in one part of the system should not affect unrelated parts.</li></ul><h4 id="strategy-pattern-">Strategy Pattern:</h4><ul><li><strong>Purpose</strong>: The <em>Strategy</em> pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It allows the algorithm to vary independently from the client that uses it.</li><li><strong>Structure</strong>: It involves defining a <em>strategy</em> interface that represents a family of algorithms, and concrete implementations of these algorithms.</li><li><strong>Use Cases</strong>: It is beneficial when there are multiple algorithms for a specific task and the client needs to select or switch between them dynamically.</li></ul><h4 id="template-method-pattern-">Template Method Pattern:</h4><ul><li><strong>Purpose</strong>: The <em>Template</em> Method pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It allows subclasses to redefine certain steps of an algorithm without changing its structure.</li><li><strong>Structure</strong>: It typically involves defining an abstract class that contains the template method (the algorithm skeleton) and abstract methods that subclasses must implement.</li><li><strong>Use Cases</strong>: It is useful when there is a common algorithm structure shared among multiple subclasses, but the specific implementation of certain steps may vary.</li></ul><p>In summary, while the <em>Bridge</em> pattern focuses on separating abstraction from implementation, the <em>Strategy</em> pattern deals with encapsulating interchangeable algorithms, and the <em>Template</em> Method pattern defines the skeleton of an algorithm with certain steps delegated to subclasses. Each pattern addresses different concerns and can be applied in different scenarios based on the specific requirements of the system.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h3 id="conclusions">Conclusions</h3><p>Some conclusions about the use of the Bridge design pattern:</p><ol><li><strong>Abstraction and Implementation Separation</strong>: The <em>Bridge</em> pattern allows for the separation of abstraction from its implementation, facilitating the modification and extension of both independently. This promotes a more flexible and scalable design.</li><li><strong>Coupling Reduction</strong>: By separating abstraction from implementation, the <em>Bridge</em> pattern helps reduce coupling between parts of the system. This makes the code easier to maintain and prevents the propagation of changes in one part of the system to unrelated parts.</li><li><strong>Support for Various Platforms</strong>: The <em>Bridge</em> pattern is especially useful when working with multiple platforms or operating systems. It allows an abstraction to have multiple implementations that are specific to each platform, facilitating adaptation to different environments.</li><li><strong>Promotion of Reusability and Modularity</strong>: By defining a hierarchy of abstraction and implementation, the <em>Bridge</em> pattern encourages code reuse and modularity. Abstractions and implementations can be easily exchanged and reused in different contexts, reducing duplication and promoting cohesion in software design.</li><li><strong>Additional Complexity</strong>: Although the <em>Bridge</em> pattern can improve code flexibility and maintainability, it also introduces an additional layer of complexity in the design. This may require extra effort to understand and maintain the code, especially in small or simple systems where the separation between abstraction and implementation may seem unnecessary.</li></ol><p>Overall, the <em>Bridge</em> pattern is a powerful tool for designing flexible and modular systems, especially when working with multiple platforms or operating systems. However, its use should be carefully evaluated based on the specific requirements of the project and the balance between flexibility and complexity in software design.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><p>The most important thing about this pattern is not the concrete implementation of it but the ability to recognize the problem that this pattern can solve and when it can be applied. The specific implementation isn’t as important since that will vary depending on the programming language used.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><p>The GitHub’s repository is the following:<br><a href="https://github.com/Caballerog/blog/tree/master/bridge-pattern">https://github.com/Caballerog/blog/tree/master/bridge-pattern</a></p>]]></content:encoded></item><item><title><![CDATA[Understanding the State Design Pattern]]></title><description><![CDATA[<p>There are 23 classic design patterns described in the original book <a href="https://amzn.to/3VN3Ygd">*Design Patterns: Elements of Reusable Object-Oriented Software</a>*. These patterns provide solutions to particular problems often repeated in software development.</p><p>In this article, I am going to describe how the <em>State</em> pattern works and when it should be applied.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="state-basic-idea">State:</h2>]]></description><link>https://www.carloscaballero.io/design-patterns-state/</link><guid isPermaLink="false">6409d7256558520001a4aa7a</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[NodeJS]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Carlos Caballero]]></dc:creator><pubDate>Mon, 10 Apr 2023 16:02:52 GMT</pubDate><content:encoded><![CDATA[<p>There are 23 classic design patterns described in the original book <a href="https://amzn.to/3VN3Ygd">*Design Patterns: Elements of Reusable Object-Oriented Software</a>*. These patterns provide solutions to particular problems often repeated in software development.</p><p>In this article, I am going to describe how the <em>State</em> pattern works and when it should be applied.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="state-basic-idea">State: Basic Idea</h2><p>Wikipedia provides us with the following definition:</p><blockquote>“The <strong>state pattern</strong> is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines. The state pattern can be interpreted as a <a href="https://betterprogramming.pub/design-patterns-using-the-strategy-pattern-in-javascript-3c12af58fd8a">strategy pattern</a>, which is able to switch a strategy through invocations of methods defined in the pattern’s interface.” — <a href="https://en.wikipedia.org/wiki/Observer_pattern">Wikipedia</a></blockquote><p>On the other hand, the definition provided by the original book is as follows:</p><blockquote>“Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.”</blockquote><p>On many occasions, we have an object which has a behavior depending on the state in which it is found. For example, when we have a purchase in an ecommerce, this purchase is started, processed, shipped, delivered, etc. The system would work differently depending on the state it is in, and this is precisely where the state design pattern can help us make our code more flexible and maintainable.</p><p>Next, let’s look at the UML class diagram of this pattern to understand each of the elements that interact in this pattern.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/3840/1*540F5K1k_uytYGUyKO95Tg.png" class="kg-image" alt="UML diagram from the book Design Patterns: Elements of Reusable Object-Oriented Software."></figure><!--kg-card-end: image--><p>These are the classes that comprise this pattern:</p><ul><li><code>Context</code> is the interface of interest to clients. This class maintains an instance of a <code>State</code> that defines the current state.</li><li><code>State</code> defines the interface for encapsulating the behavior associated with a particular state of the <code>Context</code>.</li><li><code>ConcreteStateA</code> and <code>ConcreteStateB</code> are the subclasses that implement a behavior associated with a state of the <code>Context</code>.</li></ul><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="state-pattern-when-to-use-it">State Pattern: When to Use It</h2><p>The state design pattern has the following use cases:</p><ul><li>An object’s behavior depends on its state, and it must change its behavior at runtime depending on that state.</li><li>Operations have large, multipart conditional statements that depend on the object’s state. This state is usually represented by one or more enumerated constants.</li><li>The <em>State pattern</em> puts each branch of the conditional in a separate class. This lets you treat the object’s state as an object in its own right that can vary independently from other objects.</li></ul><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="state-pattern-advantages-and-disadvantages">State Pattern: Advantages and Disadvantages</h2><p>The <em>State pattern</em> has a number of advantages, summarized in the following points:</p><ul><li>The code is more maintainable because it is **less coupled** between the object and its states. The object (<code>context</code>) only needs to know that there is a <code>State</code> which will be handled using the <code>State</code> interface.</li><li>Clean code. The <em>Open-Closed Principle</em> (OCP) is guaranteed since new states can be introduced without breaking the existing code in the chain.</li><li>Cleaner code. The <em>Single Responsibility Principle (SRP)</em> is respected since the responsibility of each state is transferred to its <code>ConcreteState</code> class instead of having that business logic in the <code>Context</code>.</li></ul><p>Finally, the main drawback of the <em>State </em> pattern — like most design patterns — is that there’s an increase in code complexity and the number of classes required for the code. With that said, this disadvantage is well known when applying design patterns — it’s the price to pay for gaining abstraction in the code.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="state-pattern-examples">State Pattern Examples</h2><p>Next, we are going to illustrate with two examples of the <em>State</em> pattern:</p><ol><li>The basic structure of the <em>State</em> pattern. In this example, we are going to translate the theoretical UML diagram into TypeScript code to identify each of the classes involved in the pattern.</li><li>The change of state of an <em><strong>anime character</strong></em>, such as the villain Freeza from Dragon Ball Z which can change its physical state through different transformations. In our case we will have up to five different states changes. Bearing in mind that between states it is possible to advance or go back one level of the transformation. However, we should have generated the state machine that we would have wanted in this process of transformations.</li></ol><p>The following examples will show the implementation of this pattern using TypeScript. We have chosen TypeScript to carry out this implementation rather than JavaScript. The latter lacks interfaces or abstract classes, so the responsibility of implementing both the interface and the abstract class would fall on the developer.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="example-1-basic-structure-of-the-state-pattern">Example 1: Basic Structure of the State Pattern</h2><p>First of all, we can see the UML class diagram of what the implementation would be like without using the <em>State</em> pattern and the problems that it tries to solve.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/2000/1*7ZBgq3wJaqarFPj5Qm8SDA.png" class="kg-image"></figure><!--kg-card-end: image--><p>In this diagram we can see that we have a <code>Context</code> class, which corresponds to the object that has different behaviors depending on the state it is in. These states can be modeled through an <code>Enum</code> class where we would have different possible states, as an example we would have two different states: <code>StateA</code> and <code>StateB</code>.</p><p>The request method of the <code>Context</code> class is where the open-closed principle is breaking since this method implements functionality based on the state the <code>Context</code> object is in. In addition to this, this method receives as a parameter a type of operation which adds conditional complexity to our problem. Even if we were to extract the behaviors of each state to external functions, we would still break this principle since every time we wanted to include a new state we would have to access this method and modify it.</p><p>Let’s see the implementation of this code to see it materialized in a programming language.</p><!--kg-card-begin: code--><pre><code class="language-TypeScript">import { State } from  "./state.enum";

export class Context {

    private state = State.stateA;

    request(operation: string) {  
        switch (this.state){
            case State.stateA:
                if(operation === 'request1'){
                    console.log('ConcreteStateA handles request1.'); //request1()
                    console.log('ConcreteStateA wants to change the state of the context.');
                    this.state = State.stateB; // Transition to another state
                    console.log(`Context: Transition to concrete-state-B.`);
                }else {
                    console.log('ConcreteStateA handles request2.'); // request2()
                }
                break
            case State.stateB:
                if(operation === 'request1'){
                    console.log('ConcreteStateB handles request1.'); //request1()
                }else{
                    console.log('ConcreteStateB handles request2.'); //request2()
                    console.log('ConcreteStateB wants to change the state of the context.');
                    this.state = State.stateA; // Transition to another state
                    console.log(`Context: Transition to concrete-state-A.`);
                }
            default: // Do nothing.
                break
        }
    }
}
</code></pre><!--kg-card-end: code--><p>In this code we can see in the request method how the <code>switch</code> control structure is implemented, which couples the code to the <code>Context</code> states. Observe that the <code>state</code> change is done in this method itself, when we change the <code>state</code> we are changing the future behavior of this method since the code corresponding to the new <code>state</code> will be accessed.</p><p>The client code that would make use of this code is to implement the following.</p><!--kg-card-begin: code--><pre><code>import { Context } from "./context";

const context = new Context();
context.request('request1');
context.request('request2');t
</code></pre><!--kg-card-end: code--><p>You can see that we simply instantiate an object of type <code>Context</code> and call the request method with different parameters. Obviously, although the result of this code is what we expect, we have all the design problems that we have mentioned above.</p><p>Now we are going to focus on solving this problem by applying the <code>State</code> pattern. Let’s start by looking at the class diagram.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/2000/1*5T4rAh2ZqvqN-qlWREW9CA.png" class="kg-image" alt="UML diagram from the book Design Patterns: Elements of Reusable Object-Oriented Software."></figure><!--kg-card-end: image--><p>The <code>Context</code> class is now related by composition to a new object that is the <code>State</code> of the context. The <code>Context</code>  will still have methods associated with the functionality it performed previously, such as <code>request1</code> and <code>request2</code>. Also, a new method, called <code>transitionTo</code> is added that will transition between the different states. That is, the change from one state to another will be done through a method that encapsulates this logic.</p><p>The <code>Context</code> class is related to an abstract class called <code>State</code>, which defines the contract that all possible states of our context must fulfill. In this specific case, two abstract methods <code>handle1</code> and <code>handle2</code> are defined, which will be specified in the concrete implementations of each of the states. That is, we are delegating the responsibility of implementing the behavior of each state to a specific subclass of said state.</p><p>On the other hand, the state class incorporates a reference to the context to be able to communicate with it to indicate that it must change its state. This reference in many implementations of the pattern does not exist, since the context reference is sent as a parameter to the methods defined in the state. We have preferred this implementation, which still respects the concept of composition and will greatly simplify the code we are showing.</p><p>Once we have seen the UML class diagram, we are going to see what the implementation of this design pattern would look like.</p><!--kg-card-begin: code--><pre><code>import { State } from "./state";

export class Context {
    private state: State;

    constructor(state: State) {
        this.transitionTo(state);
    }

    public transitionTo(state: State): void {
        console.log(`Context: Transition to ${state.constructor.name}.`);
        this.state = state;
        this.state.setContext(this);
    }

    public request1(): void {
        this.state.handle1();
    }

    public request2(): void {
        this.state.handle2();
    }
}
</code></pre><!--kg-card-end: code--><p>We start by looking at the <code>Context</code> class, and the first thing we can notice is that the state attribute is an object of the <code>State</code> class, rather than an <code>Enum</code> class. This <code>State</code> class is abstract so that responsibility can be delegated to concrete states. If we look at the <code>request1</code> and <code>request2</code> methods we see that they are making use of the state object and delegating responsibility to this class.</p><p>On the other hand, we have the implementation of the <code>transitionTo</code> method which we are going to use simply to change the state in which the <code>Context</code> is, and as we have already said to make it easier for us not to propagate the context through the handles of the state object, we are going to call the <code>setContext</code> method to assign the context to the state, making the communication between state and context permanent rather than through references between the methods.</p><p>The next step is to define the part corresponding to the states. First we see that the <code>State</code> abstract class simply defines the abstract methods that the concrete states will implement and a reference to the context.</p><!--kg-card-begin: code--><pre><code>import { Context } from "./context";

export abstract class State {
    protected context: Context;

    public abstract handle1(): void;
    public abstract handle2(): void;
}
</code></pre><!--kg-card-end: code--><p>The concrete states are those that encapsulate the business logic corresponding to each of the states when the context object is in them. If we see the code associated with these classes, we can see how the <code>ConcreteStateA</code> and <code>ConcreteStateB</code> classes implement the <code>handle1</code> and <code>handle2</code> methods corresponding to the <code>State</code> interface, and how in our specific case we are transitioning from <code>StateA</code> to <code>StateB</code> when <code>handle1</code> is executed when the context is in the <code>StateA</code> . Whereas, we transition from <code>StateB</code> to <code>StateA</code> when <code>handle2</code> is executed when the contextis in the <code>StateB</code>.</p><p>In any case, this is just an example of transitions between states, but it is important that you note that the states know each other, and that is a differentiating element of this design pattern compared to others such as the <a href="https://www.carloscaballero.io/stategy-pattern-in-javascript-typescript/">strategy pattern</a>, in which the strategies do not know each other.</p><!--kg-card-begin: code--><pre><code>import { ConcreteStateB } from "./concrete-state-B";
import { State } from "./state";

export class ConcreteStateA extends State {
    public handle1(): void {
        console.log('ConcreteStateA handles request1.');
        console.log('ConcreteStateA wants to change the state of the context.');
        this.context.transitionTo(new ConcreteStateB());
    }

    public handle2(): void {
        console.log('ConcreteStateA handles request2.');
    }
}

/*****/
import { ConcreteStateA } from "./concrete-state-A";
import { State } from "./state";

export class ConcreteStateB extends State {
    public handle1(): void {
        console.log('ConcreteStateB handles request1.');
    }

    public handle2(): void {
        console.log('ConcreteStateB handles request2.');
        console.log('ConcreteStateB wants to change the state of the context.');
        this.context.transitionTo(new ConcreteStateA());
    }
}
</code></pre><!--kg-card-end: code--><p>To conclude, we see the client class that makes use of the design pattern.</p><p>The code is almost the same as the one we had without applying the pattern except that now we are creating an initial state with which the context will be initialized.</p><!--kg-card-begin: code--><pre><code>import { ConcreteStateA } from "./concrete-state-A";
import { Context } from "./context";

const context = new Context(new ConcreteStateA()); // Initial State
context.request1();
context.request2();
</code></pre><!--kg-card-end: code--><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="example-2-dragon-ball-z-freeza-transformation">Example 2: Dragon Ball Z: Freeza Transformation</h2><p>In this example, we are going to model a Dragon Ball videogame in which we would have a beloved villain such as Freeza, who, as we know, can undergo different transformations throughout a battle.</p><p>That is to say, we will have a character called Freeza which has different states that are the transformations in which they are found, this state can change as Freeza is winning or losing in the battle. In our case, Freeza will start with a state of <code>Transformation1</code> and will be able to change his state to <code>Transformation2.</code> At that moment, the transition between states can be to return to <code>Transformation1</code> in case he is winning in battle or transition to the state of <code>Transformation3</code>. In transformation state number 3 the same thing will happen and we can transition to <code>Transformation2</code> or <code>Transformation4</code>. Finally, when we are in <code>Transformation4</code> we can return to <code>Transformation3</code> or transition to the state of <code>Golden Freeza</code> which will be the last possible state, from which we can only go backwards.</p><p>Obviously in our model we are moving back and forth, but the state machine that we can build can transition through the states as our business logic determines.</p><p>Let’s see what the class diagram for our problem might look like without applying the state design pattern.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/2000/1*TqdDyArNKHTgVd0eAWsptA.png" class="kg-image" alt="Design pattern State: Problem in which this pattern is not being used."></figure><!--kg-card-end: image--><p>The different <code>STATES</code> have been modeled with an <code>Enum</code>. That is, we will have an <code>enum</code> class where the different possible states that <code>Freeza</code> can go through are described. On the other hand, we have the <code>Freeza</code> class that models our character, this class is made up of various attributes such as <code>power</code>, <code>energy</code> and <code>state</code>. Both <code>power</code> and <code>energy</code> help us determine when to change state, and are part of the game. The methods by which Freeza is composed are:</p><ul><li><code>Constructor</code> that receives the initial state of Freeza.</li><li><code>isAlive</code> that will return a boolean value to know if Freeza is still alive.</li><li><code>transitionTo</code>, <code>attack</code> and <code>defend</code>, which are the ones with the logic associated with each of the possible states. The <code>transitionTo</code> method modifies the <code>energy</code> and <code>power</code> values depending on the state in which Freeza is, in the same way attack and defend determine the power with which Freeza attacks and defends itself, which is determined by the state in which is found.</li></ul><p>We have left as a note in the UML diagram that these methods are developed from a <code>switch-case</code> structure in which each of the cases of this structure implements the desired behavior.</p><p>Of course, here we can see how both the <em>Single Responsibility Principle</em> (SRP) and the <em>Open/Closed Principl</em>e (OCP) are violated since. First of all, SRP is violated because we have different behaviors modeled in the same class or method. Secondly, the OCP is violated because if we wanted to introduce the new Freeza transformation we would have to modify this class, and as we want to introduce new features we are forced to modify this class.</p><p>Well let’s see the concrete implementation of our problem to see how all this would be translated into code.</p><p>First of all, we see the State enum that, as we have said, only defines the different states through which Freeza can transition.</p><!--kg-card-begin: code--><pre><code>export enum State {
    TRANSFORMATION1 = 'transformation1',
    TRANSFORMATION2 = 'transformation2',
    TRANSFORMATION3 = 'transformation3',
    TRANSFORMATION4 = 'transformation4',
    GOLDEN_FREEZA = 'golden_freeza',
}
</code></pre><!--kg-card-end: code--><p>The next step is to look at the Freeza class, which has the attributes we’ve already mentioned above, and this has little to add. If we look at the constructor we can see that receiving a state that Freeza is in, we transition to that state. Another method that we have implemented is <code>isAlive</code> which checks if the Freeza energy is still greater than zero.</p><p>On the other hand, when we look at the <code>transitionTo</code> method, this is where code-smells can be detected or how the two SOLID principles are violated, since we see that this method modifies the <code>energy</code> and <code>power</code> values according to the state in which the object is found, and even if we extract this logic to auxiliary functions or methods, the logic of each of the states will still be there. That is, we will have five different states modeled in the same method.</p><p>The situation is aggravated if we see the code associated with the attack method. We once again have a switch to determine the business logic according to Freeza’s state, but as we can see, although this business logic is simple since they are simple mathematical calculations that determine the force with which it attacks an enemy, and the energy which is restored on each of your turns.</p><p>Finally, and in the same way as attack, the defend method is defined, which will again have a business logic based on the state of Freeza, but in this business logic we see that we have the transition between states. For example, in the state associated with <code>Transformation2</code>, if the <code>energy</code> value of Freeza exceeds <code>20</code>, it transitions to <code>Transformation3</code>, and on the other hand, if the energy is <code>5</code>, it transitions to <code>Transformation1</code>.</p><p>As you can see, this class makes us set off all the alarms that we need some refactoring technique.</p><!--kg-card-begin: code--><pre><code>import { State } from "./state.enum";

export class Freeza {
   
    private power: number;
    private energy: number;
    private state: State;

    constructor(state: State) {
        this.transitionTo(state);
    }

    isAlive(): boolean {
        return this.energy &gt; 0;
    }
    
    public transitionTo(state: State): void {
        console.log('-----------------------------')
        console.log(`Freeze: Transition to ${state}.`);
        console.log('-----------------------------')
        this.state = state;
        switch(state) {
            case State.TRANSFORMATION1:
                this.power = 530000;
                this.energy = 5;
            break;
            case State.TRANSFORMATION2: 
                this.power = 106000;
                this.energy = 10;
            break;
            case State.TRANSFORMATION3: 
                this.power = 212000;
                this.energy = 15;
            break;
            case State.TRANSFORMATION4:
                this.power = 106000;
                this.energy = 20;
            break;
            case State.GOLDEN_FREEZA:
                this.power = 212000;
                this.energy = 30;
            break;
        }
    }


    public attack(): void {
        let attackToEnemy, restoreEnergy;
        switch(this.state){
            case State.TRANSFORMATION1: 
                attackToEnemy = Math.round(this.power * (Math.random()/8));
                restoreEnergy = Math.round(Math.random());
                this.energy = this.energy + restoreEnergy;
                console.log('Freeza attack in the state form 1 --&gt;', attackToEnemy);
                console.log(`Freese restore energy ${restoreEnergy} and his energy is ${this.energy}\n`);
                break;
            case State.TRANSFORMATION2: 
                attackToEnemy = Math.round(this.power * (Math.random()/7));   
                restoreEnergy = Math.round(Math.random() * 2);
                this.energy = this.energy + restoreEnergy;
        
                console.log('Freeza attack in the state form 2 --&gt;', attackToEnemy);
                console.log(`Freese restore energy ${restoreEnergy} and his energy is ${this.energy}\n`);
                break;       
            case State.TRANSFORMATION3: 
                attackToEnemy = Math.round(this.power * (Math.random()/6));   
                restoreEnergy = Math.round(Math.random() * 3);
                this.energy = this.energy + restoreEnergy;
        
                console.log('Freeza attack in the state form 3 --&gt;', attackToEnemy);
                console.log(`Freese restore energy ${restoreEnergy} and his energy is ${this.energy}\n`);
    
            break;
            case State.TRANSFORMATION4:
                attackToEnemy = Math.round(this.power * (Math.random()/5));   
                restoreEnergy = Math.round(Math.random() * 4);
                this.energy = this.energy + restoreEnergy;
        
                console.log('Freeza attack in the state form 4 --&gt;', attackToEnemy);
                console.log(`Freese restore energy ${restoreEnergy} and his energy is ${this.energy}\n`);                
            break;
            case State.GOLDEN_FREEZA: 
                attackToEnemy = Math.round(this.power * (Math.random()/4));   
                restoreEnergy = Math.round(Math.random() * 5);
                this.energy = this.energy + restoreEnergy;

                console.log('Freeza attack in the state Golden Freeza --&gt;', attackToEnemy);
                console.log(`Freese restore energy ${restoreEnergy} and his energy is ${this.energy}\n`);
            break; 
        }
    }
    
    public defend(attack: number): void {
        let attackFromEnemy;

        switch(this.state){
            case State.TRANSFORMATION1: 
                attackFromEnemy = Math.round(attack * (Math.random()));
                this.energy = this.energy - attackFromEnemy;

                console.log('Freeza defend in form 1');
                console.log(`Freeza received an attack of ${attackFromEnemy} and his energy is ${this.energy}\n`);
                
            break;

            case State.TRANSFORMATION2: 
                attackFromEnemy = Math.round(attack * (Math.random()));
                this.energy = this.energy - attackFromEnemy;
                
                console.log('Freeza defend in form 2');
                console.log(`Freeza received an attack of ${attackFromEnemy} and his energy is ${this.energy}\n`);
        
                if(this.energy &lt; 5){
                    this.transitionTo(State.TRANSFORMATION1);
                }
                if(this.energy &gt; 20){
                    this.transitionTo(State.TRANSFORMATION3);
                }
            break;
            case State.TRANSFORMATION3: /* more code*/ break;
            case State.TRANSFORMATION4: /* more code*/ break;
            case State.GOLDEN_FREEZA: /* more code*/ break;

        }
    }
}
</code></pre><!--kg-card-end: code--><p>Lastly, we are going to finish by showing the code associated with the client. If you notice we only have one loop while Freeza is alive, Freeza attacks, waits a second, then Freeza defends, and so on until Freeza is no longer alive.</p><!--kg-card-begin: code--><pre><code>import { Freeza } from "./freeza";
import { State } from "./state.enum";

const sleep = (ms: number) =&gt; new Promise((r) =&gt; setTimeout(r, ms));
const freeza = new Freeza(State.TRANSFORMATION1); // Initial State

(async () =&gt; {
  while(freeza.isAlive()){
    freeza.attack();
    await sleep(1000);
    freeza.defend(10);
    await sleep(1000);
  } 
})();
</code></pre><!--kg-card-end: code--><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="example-2-dragon-ball-z-freeza-transformation-state-pattern-">Example 2: Dragon Ball Z: Freeza Transformation (State Pattern)</h2><p>We already have the context of the problem that we want to solve, now we are going to see how we can refactor the previous coupled code in a new version that will allow us to have the code with greater cohesion and allowing us to extend the project without violating the open-closed principle.</p><p>So the first thing we do is see what our project’s UML class diagram would look like by applying the state pattern.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://cdn-images-1.medium.com/max/2466/1*EcLYB3IrXd4m0Ck3zDCt9g.png" class="kg-image" alt="Dragon Ball Z: Freeza Transformation using State Pattern"></figure><!--kg-card-end: image--><p>We start by seeing that the Freeza class has the same methods as in the solution without applying the pattern. However, we can see that we now have a <code>State</code> attribute that, unlike in the previous solution, which was an <code>enum</code>, will now be an abstract class that represents the state of Freeza at a given moment. Very important, instead of being in the <code>Freeza</code> class, the <code>power</code> and <code>energy</code> attributes have been delegated to the <code>State</code> class because these two attributes change depending on the state in which the Freeza is. If any of these attributes or another attribute were not dependent on the state of the <code>Freeza</code> transformation, it would be in the <code>Freeza</code> class.</p><p>On the other hand, the novelty in this class diagram is that the <code>State</code> is now an abstract class that models the common attributes that each of the possible states in which <code>Freeza</code> is in will have, and defines the methods that encapsulate business logic different for each of the states that <code>Freeza</code> is in.</p><p>Therefore, we can see that we have the <code>power</code> and <code>energy</code> attributes defined as abstract because each of the concrete states will modify them depending on the state that Freeza is in; and here, for simplicity, we have a reference to Freeza to be able to call the <code>transitionT</code>o method in the different concrete states to transition between the states in which Freeza can be found. In this class, the abstract methods attack and defend are defined, which are the ones that will be implemented in each of the concrete states.</p><p>After defining the abstract class <code>State</code> we have to define each of the concrete states, which would be the five classes from <code>Transformation1</code> to <code>Transformation4</code> and the <code>Golden Freeza</code> transformation. Note that we have established the transition relationships between the different states, and it is very important to note that the states are known to each other, that is, the <code>states</code> that can be transitioned to are known from the origin state.</p><p>Lastly, we would have to look at the client class, which, although it is not part of the state pattern, we define it to know that this class will be the one that makes use of the State pattern, and specifically needs to know the Freeza and the initial state. Of course, if the initial state were not selected from the client, this class would only need to interact with the Freeza class without being aware of the states that the <code>Freeza</code> class may have.</p><p>Before leaving the UML class diagram, it is important to note that if we had a new Freeza transformation we would only have to implement the new state without having to modify the application. Therefore, we would be respecting the OCP since we can extend the software having it closed and protected as a base. In addition, the SRP is also respected because we have distributed the responsibility of each of the states to a specific class. Of course, our software right now is more cohesive.</p><p>And now, let’s move on to see our implemented.</p><!--kg-card-begin: code--><pre><code>import { State } from "./state";

export class Freeza {
   
    private state: State;

    constructor(state: State) {
        this.transitionTo(state);
        this.state.setFreeza(this);
    }

    isAlive(): boolean {
        return this.state.getEnergy() &gt; 0;
    }
    
    public transitionTo(state: State): void {
        console.log('-----------------------------')
        console.log(`Freeze: Transition to ${state.constructor.name}.`);
        console.log('-----------------------------')
        this.state = state;
        this.state.setFreeza(this);
    }

    public attack(): void {
        this.state.attack();
    }
    public defend(value: number): void {
        this.state.defend(value);
    }
}
</code></pre><!--kg-card-end: code--><p>Note that the Freeza class is now quite simple, there is the <code>State</code> attribute where responsibility has been delegated based on the state that Freeza is in. Note that the <code>attack</code> and <code>defend</code> methods only call the corresponding method of the abstract class, which will use one class or another depending on the state in which Freeza is. The <code>transitionTo</code> method assigns the state that Freeza is in.</p><p>Now we start to implement the Freeza states, first of all, the <code>State</code> abstract class is shown.</p><!--kg-card-begin: code--><pre><code>import { Freeza } from "./freeza";

export abstract class State {
    abstract power: number;
    abstract energy: number;
    protected freeza: Freeza;

    public setFreeza(freeza: Freeza) {
        this.freeza = freeza;
    }
    public getEnergy() {
        return this.energy;
    }

    public abstract attack(): void;
    public abstract defend(value: number): void 
}
</code></pre><!--kg-card-end: code--><p>In this class, we simply define the <code>power</code> and <code>energy</code> attributes as abstract and the <code>attack</code> and <code>defend</code> methods also as abstract since they will be the ones that are implemented in each concrete state. In addition, we have the reference to the <code>Freeza</code> object to be able to make the transition between states.</p><p>And now it would be necessary to see the implementation of the concrete states, we have defined five different states, which are the different transformations of Freeza, the logic is very simple and only for demonstration purposes. All of these states implement the <code>attack</code> and <code>defend</code> methods. In the <code>attack</code> methods, we calculate how Frieza will attack and how much energy would be restored, we are simply modifying these calculations.</p><p>On the other hand, the <code>defend</code> methods that are implemented, in our specific problem, apart from reducing the energy of Freeza, and transition between the different states. Of course, this part can be very different depending on our problem and our transition between different states.</p><p>Remember that design patterns are solutions that are repeated, and problems that appear in our software developments, but the intention of them must be understood and what problem it solves in order to later adapt them to our specific problems. So the difficulty is adapting the patterns to our specific problems, and you can’t take a solution with a design pattern and copy it directly because it probably doesn’t adapt well to our problem.</p><!--kg-card-begin: code--><pre><code>import { State } from "../state";
import { Transformation2 } from "./transformation2";

export class Transformation1 extends State {
    power = 530000;
    energy = 5;

    public attack(): void {
        const attackToEnemy = Math.round(this.power * (Math.random()/8));
        const restoreEnergy = Math.round(Math.random());
        this.energy = this.energy + restoreEnergy;
        console.log('Freeza attack in the state form 1 --&gt;', attackToEnemy);
        console.log(`Freese restore energy ${restoreEnergy} and his energy is ${this.energy}\n`);
    }

    public defend(attack: number): void {
        const attackFromEnemy = Math.round(attack * (Math.random()/7));
        this.energy = this.energy - attackFromEnemy;

        console.log('Freeza defend in form 1');
        console.log(`Freeza received an attack of ${attackFromEnemy} and his energy is ${this.energy}\n`);
  
        if(this.energy &lt; 2){
            this.freeza.transitionTo(new Transformation2());
        }
    }
}

import { State } from "../state";
import { Transformation1 } from "./transformation1";
import { Transformation3 } from "./transformation3";

export class Transformation2 extends State {
    power = 106000;
    energy = 10;
    
    public attack(): void {
        const attackToEnemy = Math.round(this.power * (Math.random()/7));   
        const restoreEnergy = Math.round(Math.random() * 2);
        this.energy = this.energy + restoreEnergy;

        console.log('Freeza attack in the state form 2 --&gt;', attackToEnemy);
        console.log(`Freese restore energy ${restoreEnergy} and his energy is ${this.energy}\n`);
    }

    public defend(attack: number) {
        const attackFromEnemy = Math.round(attack * (Math.random()/6));
        this.energy = this.energy - attackFromEnemy;
        
        console.log('Freeza defend in form 2');
        console.log(`Freeza received an attack of ${attackFromEnemy} and his energy is ${this.energy}\n`);

        if(this.energy &lt; 5){
            this.freeza.transitionTo(new Transformation3());
        }
        if(this.energy &gt; 20){
            this.freeza.transitionTo(new Transformation1());
        }
    }
}

import { State } from "../state";
import { Transformation2 } from "./transformation2";
import { Transformation4 } from "./transformation4";

export class Transformation3 extends State {
    power = 212000;
    energy = 15;
    
    public attack() {
        const attackToEnemy = Math.round(this.power * (Math.random()/6));   
        const restoreEnergy = Math.round(Math.random() * 3);
        this.energy = this.energy + restoreEnergy;

        console.log('Freeza attack in the state form 3 --&gt;', attackToEnemy);
        console.log(`Freese restore energy ${restoreEnergy} and his energy is ${this.energy}\n`);
    }

    public defend(attack: number) {
        const attackFromEnemy = Math.round(attack * (Math.random()/5));
        this.energy = this.energy - attackFromEnemy;
        
        console.log('Freeza defend in form 3');
        console.log(`Freeza received an attack of ${attackFromEnemy} and his energy is ${this.energy}\n`);

        if(this.energy &lt; 5){
            this.freeza.transitionTo(new Transformation4());
        }
        if(this.energy &gt; 25){
            this.freeza.transitionTo(new Transformation2());
        }
    }
}

import { GoldenFreeza } from "./golden-freeza";
import { State } from "../state";
import { Transformation3 } from "./transformation3";

export class Transformation4 extends State {
    power = 406000;
    energy = 20;
    
    public attack() {
        const attackToEnemy = Math.round(this.power * (Math.random()/5));   
        const restoreEnergy = Math.round(Math.random() * 4);
        this.energy = this.energy + restoreEnergy;

        console.log('Freeza attack in the state form 4 --&gt;', attackToEnemy);
        console.log(`Freese restore energy ${restoreEnergy} and his energy is ${this.energy}\n`);
    }

    public defend(attack: number) {
        const attackFromEnemy = Math.round(attack * (Math.random()/6));
        this.energy = this.energy - attackFromEnemy;
        
        console.log('Freeza defend in form 4');
        console.log(`Freeza received an attack of ${attackFromEnemy} and his energy is ${this.energy}\n`);

        if(this.energy &lt; 5){
            this.freeza.transitionTo(new GoldenFreeza());
        }
        if(this.energy &gt; 25){
            this.freeza.transitionTo(new Transformation3());
        }
    }
}

import { State } from "../state";
import { Transformation4 } from "./transformation4";

export class GoldenFreeza extends State {
    power = 812000;
    energy = 30;
    
    public attack() {
        const powerAttack = Math.round(this.power * (Math.random()/4));   
        const restoreEnergy = Math.round(Math.random() * 5);
        this.energy = this.energy + restoreEnergy;

        console.log('Freeza attack in the state Golden Freeza --&gt;', powerAttack);
        console.log(`Freese restore energy ${restoreEnergy} and his energy is ${this.energy}\n`);
    }

    public defend(attack: number) {
        const attackFromEnemy = Math.round(attack * (Math.random()/5));
        this.energy = this.energy - attackFromEnemy;
        
        console.log('Freeza defend in Golden Freeza');
        console.log(`Freeza received an attack of ${attackFromEnemy} and his energy is ${this.energy}\n`);

        if(this.energy &gt; 50){
            this.freeza.transitionTo(new Transformation4());
        }
    }
}
</code></pre><!--kg-card-end: code--><p>The last step would be to see the class that makes use of our <code>Freeza</code> object. This class is often called the client, and in our case it hasn’t changed at all between the version without and with the application of the design pattern.</p><!--kg-card-begin: code--><pre><code>import { Freeza } from "./freeza";
import { Transformation1 } from "./states/transformation1";

const sleep = (ms: number) =&gt; new Promise((r) =&gt; setTimeout(r, ms));
const freeza = new Freeza(new Transformation1()); // Initial State

(async () =&gt; {
  while(freeza.isAlive()){
    freeza.attack();
    await sleep(1000);
    freeza.defend(10);
    await sleep(1000);
  } 
})();
</code></pre><!--kg-card-end: code--><p>Finally, I’ve created several <code>npm scripts</code> through which the code presented in this article can be executed:</p><!--kg-card-begin: code--><pre><code>npm run example1-problem
npm run example1-state-solution-1

npm run example2-problem
npm run example2-state-solution-1
</code></pre><!--kg-card-end: code--><p>See this <a href="https://github.com/Caballerog/blog/tree/master/state-pattern">GitHub repo</a> for the full code.</p><!--kg-card-begin: hr--><hr><!--kg-card-end: hr--><h2 id="conclusion">Conclusion</h2><p>State is a design pattern that allows you to respect the Open-Closed Principle since a new State can be created without breaking the existing code. In addition, this allows you to comply with the Single Responsibility Principle (SRP) since each State only has a single responsibility to resolve. Another very interesting point of this pattern is that the states can interact with each other, transitioning between the different states.</p><p>The most important thing about this pattern is not the concrete implementation of it but the ability to recognize the problem that this pattern can solve and when it can be applied. The specific implementation isn’t as important since that will vary depending on the programming language used.</p>]]></content:encoded></item><item><title><![CDATA[Understanding the Chain of Responsibility Design Pattern]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>There are 23 classic design patterns described in the original book <a href="https://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612"><em>Design Patterns: Elements of Reusable Object-Oriented Software</em></a>. These patterns provide solutions to particular problems often repeated in software development.</p>
<p>In this article, I am going to describe how the <em>Chain of Responsibility</em> pattern works and when it should be</p>]]></description><link>https://www.carloscaballero.io/understanding-the-chain-of-responsibility-design-pattern/</link><guid isPermaLink="false">60bd07531d7b7a00018a1c94</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Carlos Caballero]]></dc:creator><pubDate>Mon, 20 Feb 2023 18:08:12 GMT</pubDate><media:content url="http://www.carloscaballero.io/content/images/2021/06/1_SWaUQmqenK-Twz5UuP12Eg.jpeg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><img src="http://www.carloscaballero.io/content/images/2021/06/1_SWaUQmqenK-Twz5UuP12Eg.jpeg" alt="Understanding the Chain of Responsibility Design Pattern"><p>There are 23 classic design patterns described in the original book <a href="https://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612"><em>Design Patterns: Elements of Reusable Object-Oriented Software</em></a>. These patterns provide solutions to particular problems often repeated in software development.</p>
<p>In this article, I am going to describe how the <em>Chain of Responsibility</em> pattern works and when it should be applied.</p>
<hr>
<h2 id="responsibilityofchainbasicidea">Responsibility of Chain: Basic Idea</h2>
<p>Wikipedia provides us with the following definition:</p>
<blockquote>
<p>“The <strong>chain-of-responsibility pattern</strong> is a <a href="https://en.wikipedia.org/wiki/Design_pattern_(computer_science)">design pattern</a> consisting of a source of <a href="https://en.wikipedia.org/wiki/Command_pattern">command objects</a> and a series of <strong>processing objects</strong>. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.” — <a href="https://en.wikipedia.org/wiki/Observer_pattern">Wikipedia</a></p>
</blockquote>
<p>On the other hand, the definition provided by the original book is as follows:</p>
<blockquote>
<p>“Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.”</p>
</blockquote>
<p>On many occasions, we have a set of <code>handlers</code> (operations) that can be applied to an object (<code>request</code>) but we do not know, <em>a priori</em>, which handler should be applied to said object, nor whether one or more handlers should be applied to the request. The chain of responsibility pattern allows us to achieve more efficient and less coupled code since it avoids the previously mentioned issue. It also has other advantages regarding code maintainability. Here’s the UML pattern of this pattern:</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/0*1BAs1LZrgi_Ot0qO.png" alt="Understanding the Chain of Responsibility Design Pattern"></p>
<p>These are the classes that comprise this pattern:</p>
<ul>
<li>
<p><code>Handler</code> is the interface for handling requests. Although optional, most implementations also specify the successor link.</p>
</li>
<li>
<p><code>ConcreteHandler</code> are the concrete implementations that are responsible for handling the requests. Also, it can access its successor. The behavior of these classes is quite simple: if it can handle the request it will do it, otherwise, it will delegate the responsibility to the next handler.</p>
</li>
<li>
<p>Client is responsible for initiating the sequence of request handlers (<code>ConcreteHandler</code>).</p>
</li>
</ul>
<hr>
<h2 id="responsibilityofchainwhentouseit">Responsibility of Chain: When to Use It</h2>
<ul>
<li>
<p>When there is more than one object that can handle a request, and it happens that the handler is not known a priori. Also, we need the handler to be selected automatically.</p>
</li>
<li>
<p>The set of objects that can handle a request can be specified dynamically.</p>
</li>
<li>
<p>A request is handled by one or more objects without explicitly specifying the recipient.</p>
</li>
</ul>
<hr>
<h2 id="chainofresponsibilitypatternadvantagesanddisadvantages">Chain of Responsibility Pattern: Advantages and Disadvantages</h2>
<p>The chain of responsibility pattern has a number of advantages, summarized in the following points:</p>
<ul>
<li>
<p>The code is more maintainable because it is <strong>less coupled</strong> between the object and the other object handles a request. The object (sender) only needs to know that a request will be handled by the handler. That is to say that both (receiver and the sender) have no explicit knowledge of each other. Besides, the object in the chain doesn’t need to know about the chain’s structure.</p>
</li>
<li>
<p>Clean code. The <em>Open-Closed Principle</em> (OCP) is guaranteed since new handlers can be introduced without breaking the existing code in the chain.</p>
</li>
<li>
<p>Cleaner code. The <em>Single Responsibility Principle (SRP)</em> is respected since the responsibility of each handler is transferred to its handle method instead of having that business logic in the client code.</p>
</li>
</ul>
<p>A well-known drawback of this pattern is that the <em>receipt isn’t guaranteed</em>. That’s due to the fact that the request has no explicit receiver. Therefore, the request can fall off the end of the chain without ever being handled.</p>
<p>Finally, the main drawback of the chain of responsibility pattern — like most design patterns — is that there’s an increase in code complexity and the number of classes required for the code. With that said, this disadvantage is well known when applying design patterns — it’s the price to pay for gaining abstraction in the code.</p>
<hr>
<h2 id="responsibilityofchainexamples">Responsibility of Chain Examples</h2>
<p>Next, we are going to illustrate with two examples of the Responsibility of Chain pattern:</p>
<ul>
<li>
<p>The basic structure of the Responsibility of Chain pattern. In this example, we are going to translate the theoretical UML diagram into TypeScript code to identify each of the classes involved in the pattern.</p>
</li>
<li>
<p>A <em>middleware-based authentication system</em>. Three middlewares are developed that allow validating the existence of a user, password-based authentication, and finally the role of the user.</p>
</li>
</ul>
<p>The following examples will show the implementation of this pattern using TypeScript. We have chosen TypeScript to carry out this implementation rather than JavaScript. The latter lacks interfaces or abstract classes, so the responsibility of implementing both the interface and the abstract class would fall on the developer.</p>
<hr>
<h2 id="example1basicstructureoftheresponsibilityofchainpattern">Example 1: Basic Structure of the Responsibility of Chain Pattern</h2>
<p>In this first example, we’re going to translate the theoretical UML diagram into TypeScript to test the potential of this pattern. This is the diagram to be implemented:</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*Gwb_u0VQZUxkRZL9tU_tcA.jpeg" alt="Understanding the Chain of Responsibility Design Pattern"></p>
<p>First, we are going to define the interface (<code>Handler</code>) of our problem. This interface defines two methods <code>next</code> and <code>handle</code>. The first method is in charge of linking each handler with the next. While the second method is in charge of carrying out the specific operation of each of the handlers.</p>
 <iframe src="https://medium.com/media/5eacaaadbd0c46300a783049ffc8f7a7" frameborder="0"></iframe>
<p>The next class to define is <code>AbstractHandler</code>. This class implements the interface and is, by definition, abstract — because there can be methods that are implemented in concrete classes. Normally, the abstract method is the one that handles the request (<code>handler</code>). However, in our concrete example we have implemented this function in such a way as to check that if there is a following handler, pass it on the responsibility of handling the request, and in the event that there are no more handlers, we simply stop in the chain of responsibility.</p>
<p>Another interesting point is to see how there is a reflexive relationship that allows defining the <code>nextHandler</code> attribute, which is the next handler in the chain. Finally, this class defines the assignment accessor method for the <code>nextHandler</code> attribute.</p>
 <iframe src="https://medium.com/media/61d30d2125e7ba521890e0da213a92e8" frameborder="0"></iframe>
<p>The next step is to define each of the concrete handlers, which will extend from the abstract class but will have concrete implementations of the handle method. Specifically, we can see that in the basic example what we do is check in each of the handlers if the request they receive corresponds to the one they know how to manage, and if not, we derive the responsibility to the next handler of the chain of responsibility through the method implemented in the <code>AbstractHandler</code> class.</p>
 <iframe src="https://medium.com/media/4ee01997eebd875d1d463592a09b9dcd" frameborder="0"></iframe>
<p>Finally, we have to define the client code, which makes use of this pattern. In this case, we are going to declare the three handlers (<code>HandlerA</code>, <code>HandlerB</code> and <code>HandlerC</code>), and assign the order of the following responsibility chain the following order: <code>A → B → C</code>.</p>
<p>Later, we’ll simulate three requests for each of the handlers through the auxiliary function <code>ClientCode</code>.</p>
<p>In the first case, you can see how the three options have been managed and the managers who are responsible for them.</p>
<p>In the second case, we are going to omit <code>HandlerA</code> from the chain of responsibility and repeat the three requests again. The result will be that neither <code>HandlerB</code> nor <code>HandlerC</code> is able to handle the request corresponding to <code>OptionA</code>.</p>
 <iframe src="https://medium.com/media/a71c9a043ea746a9ef3eff7a1413d02a" frameborder="0"></iframe>
<hr>
<h2 id="example2middlewaresusingchainofresponsibility">Example 2: Middlewares Using Chain of Responsibility</h2>
<p>In this example, we are going to use the chain of responsibility pattern to simulate an authentication and authorization system using a set of middlewares that applies checks on a request.</p>
<p>As we did in the previous example, let’s start by taking a look at the UML diagram that is going to help us identify each of the parts that this pattern is composed of.</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*PFIpJSvhYk0PCvotg7eY6Q.jpeg" alt="Understanding the Chain of Responsibility Design Pattern"></p>
<p>Notice that our class diagram incorporates some extra classes. These give context to our problem, but the chain of responsibility pattern can easily be identified among the set of classes.</p>
<p>Before we address the implementation of our problem, let’s define a set of constants that will give us semantic value to these values. These three constants are quite simple: Firstly, we have two fake users (<code>USERS</code>), secondly, the number of maximum authentication requests per minute (<code>REQUEST_PER_MINUTE</code>), and finally the waiting time in milliseconds when the number of requests per minute is exceeded (<code>WAIT_TIME</code>).</p>
 <iframe src="https://medium.com/media/47cbf4ef185d184f65bc8061f3725836" frameborder="0"></iframe>
<p>We start to define the pattern again by defining the <code>Handler</code> interface with the same two methods as in the basic structure of the pattern. In other words, the <code>Handler</code> interface is made up of the <code>setNextMiddleware</code> and execute methods, the first being in charge of linking each of the middleware and the second method is responsible for handling the request.</p>
<p>In our case, the request that we have to handle is the one composed by a <code>User</code>.</p>
 <iframe src="https://medium.com/media/032b102e744f1bfa8e9726f43711ed99" frameborder="0"></iframe>
<p>The objects that behave as users must satisfy the <code>User</code> interface, which is simply composed of an <code>email</code> and a <code>password</code>. The goal of this tutorial is to understand the chain of responsibility pattern, so this part will be simple — but complete enough to solve the authentication and authorization problem.</p>
 <iframe src="https://medium.com/media/780d7d0ea24b3258f86f1590c1f8c472" frameborder="0"></iframe>
<p>Continuing with the pattern, the next element is the development of the abstract class, <code>Middleware</code>, that implements the <code>Handler interface</code>. In this implementation, there is the <code>setNextMiddleware</code> method, which allows linking the following middleware, and the execute method, which is abstract and is implemented in each of the specific middleware. Finally, we have the <code>checkNext</code> method that checks if we have reached the end of the middleware chain, responding true when all the checks have been passed. If there is a next middleware then the next middleware check will be executed.</p>
 <iframe src="https://medium.com/media/b4daf2177a787d651319aa5c3622a3b0" frameborder="0"></iframe>
<p>The first middleware we need to build for the authentication and authorization system is verification that the user exists.</p>
<p>In our example, we have modeled a fake server where we have two registered users (the same ones that we previously defined in the constants). This server, which we will see later, provides us an API with the <code>hasEmail</code> and <code>isValidPassword</code> methods. The execute method will receive the request (a <code>User</code>) and we would make the checks to ensure the user exists on the server. First, it checks if the email exists on the server; if so, the <code>username</code> and <code>password</code> are checked. If the check is passed, the <code>checkNext</code> method is executed, which consists of making the request to the next middleware.</p>
 <iframe src="https://medium.com/media/94c3ef04e4f156408fe56be5bc52d12b" frameborder="0"></iframe>
<p>The following middleware would be the one that allows us to control the number of requests per minute.</p>
<p>This is where you can see the Open-Close Principle (OCP) — it is very easy to incorporate new middleware and checks without breaking the existing code. You can also see the Single Responsibility Principle(SRP) since each middleware has only one responsibility.</p>
<p>In this middleware, we receive the maximum number of requests per minute as a parameter. In addition, this middleware has some private attributes that allow you to control the time that has passed between requests, and the number of attempts that have been made in one minute.</p>
<p>If you look at the logic of the execute method, it’s quite simple — but you can check how a check exists again. This is what stops the chain of responsibility since it’s resolved by this handler.</p>
<p>In case the check is passed, this middleware, like the previous one, will proceed to pass the request to the next middleware.</p>
 <iframe src="https://medium.com/media/cef403f5a214d86ca440241ccb7624c7" frameborder="0"></iframe>
<p>Finally, the following middleware is in charge of checking if the user is an administrator or not, obviously, this should have been done with a real check on a knowledge base. However, to illustrate that each middleware can have different parameters, a basic check has been performed.</p>
<p>In the case of being admin, the chain of responsibility is finished. Otherwise, it continues. This is so that when a new middleware is developed, it can be managed in the chain. In our case, here we end the responsibility chain because we do not have any more middleware implemented.</p>
 <iframe src="https://medium.com/media/6763771f630df1a41c455c7731cb3d02" frameborder="0"></iframe>
<p>For educational purposes, we have built a <code>Server</code> class that stores users on a <code>Map&lt;String, User&gt;</code> and has a Middleware that is the one that begins the chain of responsibility.</p>
<p>The register, <code>hasEmail</code> and <code>isValidPassword</code> methods are focused on performing these operations using the users who are registered on the server.</p>
<p>The <code>logIn</code> method receives the request with the <code>user</code>. The chain of responsibility begins on line 13 with the execution of the middleware sending the <code>user</code> as a request.</p>
 <iframe src="https://medium.com/media/2707d3a7d38cf3d3ac1816c1326150bc" frameborder="0"></iframe>
<p>Finally, the client that makes use of our middleware system is the one shown in the code. A server has been created and two user accounts registered, obviously this would be our real backend and should not have been done here.</p>
<p>Subsequently, the chain of responsibilities is indicated using the following middleware in the following order:</p>
<pre><code class="language-javascript">UserExists -&gt; Trottling -&gt; Role
</code></pre>
<p>Finally, we have created a loop in which <code>email</code> and <code>password</code> are requested.</p>
 <iframe src="https://medium.com/media/c4ff115cafc7c4989dd8b26e2bc605c8" frameborder="0"></iframe>
<p>To end this article we are going to see the code working and for this I have recorded several GIFs.</p>
<p>In the first, we can see the UserExists and Throttling middleware in operation. I have entered the wrong email and password several times, the first middleware (Throttling) will leave the responsibility the first two times to the UserExists middleware, which rejects the validation of the user/password. From the third time the credentials are entered, the Throttling middleware will be in charge of managing the request.</p>
<p><img src="https://cdn-images-1.medium.com/max/2410/1*VMcc8xfpBtdQfTm0BXSBiw.gif" alt="Understanding the Chain of Responsibility Design Pattern"></p>
<p>The role middleware is the one that manages the request when the credentials corresponding to the admin role are entered.</p>
<p><img src="https://cdn-images-1.medium.com/max/2410/1*WXB_BYdK9s94pLk2vjI0sQ.gif" alt="Understanding the Chain of Responsibility Design Pattern"></p>
<p>Finally, I’ve created two npm scripts through which the code presented in this article can be executed:</p>
<pre><code class="language-javascript">    npm run example1
    npm run example2
</code></pre>
<p>See this <a href="https://github.com/Caballerog/blog/tree/master/chain-responsibility-pattern">GitHub repo</a> for the full code.</p>
<hr>
<h2 id="conclusion">Conclusion</h2>
<p>Chain of responsibility is a design pattern that allows you to respect the Open-Closed Principle since a new Handler can be created without breaking the existing code. In addition, this allows you to comply with the Single Responsibility Principle (SRP) since each handler only has a single responsibility to resolve. Another very interesting point of this pattern is that it is not necessary to know, <em>a priori</em>, which handler should resolve the request, which allows you to make the decision at runtime.</p>
<p>The most important thing about this pattern is not the concrete implementation of it but the ability to recognize the problem that this pattern can solve and when it can be applied. The specific implementation isn’t as important since that will vary depending on the programming language used.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Understanding the Observer Design Patterns]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>There are 23 classic design patterns which are described in the original book Design Patterns: Elements of Reusable Object-Oriented Software. These patterns provide solutions to particular problems often repeated in software development.</p>
<p>In this article, I am going to describe how the <strong>Observer Pattern</strong> works and when it should be</p>]]></description><link>https://www.carloscaballero.io/understanding-the-observer-design-patterns/</link><guid isPermaLink="false">5ff0fc88886c5e00010dff79</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[NodeJS]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Carlos Caballero]]></dc:creator><pubDate>Tue, 27 Apr 2021 22:18:32 GMT</pubDate><media:content url="http://www.carloscaballero.io/content/images/2021/01/sergey-semin-ZuXDaoIx_Bc-unsplash.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><img src="http://www.carloscaballero.io/content/images/2021/01/sergey-semin-ZuXDaoIx_Bc-unsplash.jpg" alt="Understanding the Observer Design Patterns"><p>There are 23 classic design patterns which are described in the original book Design Patterns: Elements of Reusable Object-Oriented Software. These patterns provide solutions to particular problems often repeated in software development.</p>
<p>In this article, I am going to describe how the <strong>Observer Pattern</strong> works and when it should be applied.</p>
<hr>
<h1 id="observerpatternbasicidea">Observer Pattern: Basic Idea</h1>
<p>Wikipedia provides us with the following definition:</p>
<blockquote>
<p>The <strong>observer pattern</strong> is a <a href="https://en.wikipedia.org/wiki/Design_pattern_(computer_science)">software design pattern</a> in which an <a href="https://en.wikipedia.org/wiki/Object_(computer_science)#Objects_in_object-oriented_programming">object</a>, named the <strong>subject</strong>, maintains a list of its dependents, called <strong>observers</strong>, and notifies them automatically of any state changes, usually by calling one of their <a href="https://en.wikipedia.org/wiki/Method_(computer_science)">methods</a>. — <a href="https://en.wikipedia.org/wiki/Observer_pattern">Wikipedia</a></p>
</blockquote>
<p>On the other hand, the definition provided by the original book is the following:</p>
<blockquote>
<p>Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. — Design Patterns: Elements of Reusable Object-Oriented Software</p>
</blockquote>
<p>On many occasions we need to communicate system objects without coupling them either at code or at communication mechanism level. Should we have a group of objects (observers) that are required to be aware of the state of another object (observable), there are different techniques for carrying out  the communication between them. The most popular techniques are:</p>
<ol>
<li>
<p><strong>Busy waiting</strong>. A process repeatedly verifies a condition. In our case, it would be an observer constantly checking whether or not the observable's condition has changed. This strategy could be a valid solution in certain cases, but it isn't an adequate solution for our scenario, since it would imply having several processes (observers) consuming resources without performing any operations, causing an exponential performance decrease in the number of existing observers.</p>
</li>
<li>
<p><em><strong>Polling</strong></em>. In this case, the query operation is performed with a small window of time between operations. This is an attempt to implement synchronism between processes. However, we can once again appreciate degradation in the system's performance, furthermore, depending on the time set between each query, the information can be so delayed that it might be invalid causing a wastage of resources used by this technique.</p>
</li>
</ol>
<p>The following codes show implementations of the previous techniques:</p>
<p><strong>Busy-Waiting:</strong></p>
<pre><code class="language-javascript">while(!condition){
   // Query
   if(isQueryValid) condition = true;
}
</code></pre>
<p><strong>Polling:</strong></p>
<pre><code class="language-javascript">function refresh() {
    setTimeout(refresh, 5000);
    // Query
}

// initial call, or just call refresh directly
setTimeout(refresh, 5000);
</code></pre>
<p>Although it isn't the goal of this post, it's a good idea to understand the two alternative techniques to this design pattern. Therefore, we can say that, in a nutshell, the difference between the active wait and polling techniques is that in the former the query operation is performed all the time, while in the latter there are intervals of time where the operation isn't executed.</p>
<p><strong>Busy-Waiting:</strong></p>
<pre><code class="language-javascript">while(resourceIsNotReady()){
  //Do nothing
}
</code></pre>
<p><strong><em>Polling</em>:</strong></p>
<pre><code class="language-javascript">while(resourceIsNotReady()){
     Sleep(1000); // 1000 or anytime
 }
</code></pre>
<p>The <strong>Observer</strong> pattern allows us to achieve a more efficient and less coupled code, since it avoids the previously mentioned issue, as well as having other advantages regarding code maintainibility. The UML pattern of this pattern is the following:</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*Dk6aMlxBYXBPdFq4Ftxi2A.gif" alt="Understanding the Observer Design Patterns"></p>
<p>The classes that comprise this pattern are the following:</p>
<ul>
<li>
<p><strong>Subject</strong> is the interface that every <strong>observed</strong> class implements. This interface contains the <code>attach</code> and <code>detach</code> methods that allow us to add and remove observers from the class. It also contains a <code>notify</code> method, which is responsible for notifying all of the observers that a change has occurred in the observed. Also, all of the <code>subject</code>s store references of the objects that observe them (<code>observers</code>).</p>
</li>
<li>
<p><strong>Observer</strong> is the interface that all of the <code>ConcreteObserver</code>s implement. In this interface, the <code>update</code> method is defined, which contains the business logic to be executed by each observer upon receiving the change notification from the <code>Subject</code>.</p>
</li>
<li>
<p><strong>ConcreteSubject</strong> is the concrete implementation of the <code>Subject</code> class.<br>
This class defines the state of the <code>SubjectState</code> application, which must be notified when a change occurs. For this reason, the accessor methods (<code>getState</code> and <code>setState</code>) are usually implemented, since they manipulate the state. This class is also responsible for sending the notification to all of its observers when the state changes.</p>
</li>
<li>
<p><strong>ConcreteObserver</strong> is the class that models each of the concrete observers. In this class the <code>update</code> method belonging to the <code>Observer</code> interface is implemented, which is responsible for maintaining its state consistently which is responsible for keeping its state consistent with the <code>subject</code> objects it is observing.</p>
</li>
</ul>
<p>Nowadays there's a family of libraries known as <a href="https://en.wikipedia.org/wiki/ReactiveX"><em><strong>Reactive Extensions or ReactiveX</strong></em></a> which have made this design pattern popular. The <em>Reactive Extensions</em> make use of two design patterns: 1) Observer 2) <a href="https://medium.com/better-programming/understanding-the-iterator-pattern-in-javascript-typescript-using-symbol-iterator-ab400d46b14a">Iterator</a>. They also have a group of operators that use functional programming. These are some of the most popular <em>Reactive Exntensions</em>:</p>
<ul>
<li>
<p>Java: <a href="https://github.com/ReactiveX/RxJava">RxJava</a></p>
</li>
<li>
<p>JavaScript: <a href="https://github.com/ReactiveX/rxjs">RxJS</a></p>
</li>
<li>
<p>C#: <a href="https://github.com/Reactive-Extensions/Rx.NET">Rx.NET</a></p>
</li>
<li>
<p>C#(Unity): <a href="https://github.com/neuecc/UniRx">UniRx</a></p>
</li>
</ul>
<p>In these implementations, there are differences in the naming of classes and methods. The following names are the most extended:</p>
<ol>
<li>
<p><code>Subscriber</code> corresponds with the class <code>Observer</code>.</p>
</li>
<li>
<p><code>ConcreteSubscribers</code> correspond with the classes <code>ConcreteObservers</code>.</p>
</li>
<li>
<p>The <code>Subject</code> class is maintained. The <code>attach</code> and <code>detach</code> methods are renamed to <code>subscribe</code> and <code>unsubscribe</code>.</p>
</li>
<li>
<p>The <code>ConcreteSubjects</code> classes are concrete implementations, like <code>BehaviorSubject</code>, <code>ReplaySubject</code> o <code>AsyncSubject</code>.</p>
</li>
</ol>
<hr>
<h1 id="observerpatterncommunicationstrategies">Observer Pattern: Communication Strategies</h1>
<p>There are two communication strategies between <code>Subject</code>s (observables) and  <code>Observer</code>s (observadores) in the observer pattern:</p>
<ul>
<li>
<p><strong>Pull</strong>. In this model, the <code>subject</code> sends the minimum information to the observers and they are responsible for making inquiries to obtain more detail. This model focuses on the fact that the <code>Subject</code> ignores the <code>observers</code>.</p>
</li>
<li>
<p><strong>Push</strong>. In this model, the <code>subject</code> sends the greatest amount of information to the <code>observers</code> the information of the change produced, regardless of whether they wanted it or not. In this model, the <code>Subject</code> knows in depth the needs of each of its <code>observers</code>.</p>
</li>
</ul>
<p>Although a priori it may seem that the <em>push</em> communication technique is less reusable due to the fact that the <code>Subject</code> must have knowledge about the <code>observers</code>, this is not always the case. On the other hand, the <em>pull</em> based communication technique can be inefficient because the <code>observers</code> have to figure out what changed without help from the <code>Subject</code>.</p>
<hr>
<h1 id="observerpatternwhentouse">Observer Pattern: When To Use</h1>
<ol>
<li>
<p>When there is a one-to-many dependency between system objects so that when the object changes state, all dependent objects need to be notified automatically.</p>
</li>
<li>
<p>You do not want to use [busy-waiting] (<a href="https://en.wikipedia.org/wiki/Busy_waiting">https://en.wikipedia.org/wiki/Busy_waiting</a>) and [Polling] (<a href="https://en.wikipedia.org/wiki/Polling_(computer_science)">https://en.wikipedia.org/wiki/Polling_(computer_science)</a>) to update observers.</p>
</li>
<li>
<p>Decouple the dependencies between the <code>Subject</code> objects (Observables) and the <code>Observers</code> (Observers) allowing to respect the <em>Open-Closed Principle</em>.</p>
</li>
</ol>
<hr>
<h1 id="observerpatternadvantagesanddisadvantages">Observer Pattern: Advantages and Disadvantages</h1>
<p>The <em>Observer</em> pattern has a number of advantages that can be summarized in the following points:</p>
<ul>
<li>
<p>The code is more maintainable because it is less coupled between the <em>observable</em> classes and their dependencies (the <em>observers</em>).</p>
</li>
<li>
<p><strong>Clean code</strong> since the <em>Open-Closed Principle</em> is guaranteed due to the new observers (subscribers) can be introduced without breaking the existing code in the observable (and vice versa).</p>
</li>
<li>
<p><strong>Cleaner code</strong> because the <em>Single Responsibility Principle (SRP)</em> is respected since the responsibility of each observer is transferred to its <code>update</code> method instead of having that business logic in the Observable object.</p>
</li>
<li>
<p>Relationships between objects can be established at runtime rather than at compile time.</p>
</li>
</ul>
<p>However, the main drawback of the <em>observer</em> pattern, like most design patterns, is that there is an increase in complexity in the code, and an increase in the number of classes required for the code. Although, this disadvantage is well known when applying design patterns since the price to pay for gaining abstraction in the code.</p>
<hr>
<h1 id="observerpatternexamples">Observer Pattern Examples</h1>
<p>Next, we are going to illustrate two examples of application of the <em>Observer</em> pattern:</p>
<ol>
<li>
<p>Basic structure of the <em>Observer</em> pattern. In this example we are going to translate the theoretical UML diagram into TypeScript code to identify each of the classes involved in the pattern.</p>
</li>
<li>
<p>An auction system in which there is an object (<code>subject</code>) that emits the change produced (<code>push</code> technique) in the <code>price</code> of a <code>product</code> that is being auctioned to all observers (<code>observer</code>) interested in acquiring that <code>product</code>. Every time the <code>price</code> of the <code>product</code> auction increases because some observer has increased the bid, it is notified to all observers.</p>
</li>
</ol>
<p>The following examples will show the implementation of this pattern using <strong>TypeScript</strong>. We have chosen TypeScript to carry out this implementation rather than JavaScript — the latter lacks interfaces or abstract classes so the responsibility of implementing both the interface and the abstract class would fall on the developer.</p>
<hr>
<h2 id="example1basicstructureoftheobserverpattern">Example 1: Basic structure of the observer pattern</h2>
<p>In this first example, we're going to translate the theoretical UML diagram into TypeScript to test the potential of this pattern. This is the diagram to be implemented:</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*qNlF1YbirVKOjCaIGgihnQ.jpeg" alt="Understanding the Observer Design Patterns"></p>
<p>First, we are going to define the interface (<code>Subject</code>) of our problem. Being an interface, all the methods that must be implemented in all the specific <code>Subject</code> are defined, in our case there is only one <code>ConcreteSubject</code>. The <code>Subject</code> interface defines the three methods necessary to comply with this pattern: <code>attach</code>, <code>detach</code> and <code>notify</code>. The <code>attach</code> and <code>detach</code> methods receive the <code>observer</code> as a parameter that will be added or removed in the <code>Subject</code> data structure.</p>
<pre><code class="language-javascript">import { Observer } from &quot;./observer.interface&quot;;

export interface Subject {
  attach(observer: Observer): void;
  detach(observer: Observer): void;
  notify(): void;
}
</code></pre>
<p>There can be as many <code>ConcreteSubject</code> as we need in our problem. As this problem is the basic scheme of the <em>Observer</em> pattern, we only need a single <code>ConcreteSubject</code>. In this first problem, the state that is observed is the state attribute, which is of type number. On the other hand, all <code>observers</code> are stored in an array called <code>observers</code>. The <code>attach</code> and <code>detach</code> methods check whether or not the <code>observer</code> is previously in the data structure to add or remove it from it. Finally, the <code>notify</code> method is in charge of invoking the <code>update</code> method of all the <code>observers</code> that are observing the <code>Subject</code>.</p>
<p>Objects of the <code>ConcreteSubject</code> class perform some task related to the specific business logic of each problem. In this example, there is a method called <code>operation</code> that is in charge of modifying the <code>state</code> and invoking the <code>notify</code> method.</p>
<pre><code class="language-javascript">import { Observer } from &quot;./observer.interface&quot;;
import { Subject } from &quot;./subject.interface&quot;;

export class ConcreteSubject implements Subject {
  public state: number;
  private observers: Observer[] = [];

  public attach(observer: Observer): void {
    const isAttached = this.observers.includes(observer);
    if (isAttached) {
      return console.log(&quot;Subject: Observer has been attached already&quot;);
    }

    console.log(&quot;Subject: Attached an observer.&quot;);
    this.observers.push(observer);
  }

  public detach(observer: Observer): void {
    const observerIndex = this.observers.indexOf(observer);
    if (observerIndex === -1) {
      return console.log(&quot;Subject: Nonexistent observer&quot;);
    }

    this.observers.splice(observerIndex, 1);
    console.log(&quot;Subject: Detached an observer&quot;);
  }

  public notify(): void {
    console.log(&quot;Subject: Notifying observers...&quot;);
    for (const observer of this.observers) {
      observer.update(this);
    }
  }

  public operation(): void {
    console.log(&quot;Subject: Business Logic.&quot;);
    this.state = Math.floor(Math.random() * (10 + 1));

    console.log(`Subject: The state has just changed to: ${this.state}`);
    this.notify();
  }
}
</code></pre>
<p>The other piece of this design pattern is the <code>observer</code>. Therefore, let's start by defining the <code>Observer</code> interface which only needs to define the <code>update</code> method which is in charge of executing every time an <code>observer</code> is notified that a change has occurred.</p>
<pre><code class="language-javascript">import { Subject } from &quot;./subject.interface&quot;;

export interface Observer {
  update(subject: Subject): void;
}
</code></pre>
<p>Each class that implements this interface must include its business logic in  the <code>update</code> method. In this example two <code>ConcreteObserver</code>s have been defined, which will perform actions according to the <code>Subject</code>s state. The following code shows two concrete implementations for two different types of observers: <code>ConcreteObserverA</code> and <code>ConcreteObserverB</code>.</p>
<pre><code class="language-javascript">import { ConcreteSubject } from &quot;./concrete-subject&quot;;
import { Observer } from &quot;./observer.interface&quot;;
import { Subject } from &quot;./subject.interface&quot;;

export class ConcreteObserverA implements Observer {
  public update(subject: Subject): void {
    if (subject instanceof ConcreteSubject &amp;&amp; subject.state &lt; 3) {
      console.log(&quot;ConcreteObserverA: Reacted to the event.&quot;);
    }
  }
}
</code></pre>
<pre><code class="language-javascript">import { ConcreteSubject } from &quot;./concrete-subject&quot;;
import { Observer } from &quot;./observer.interface&quot;;
import { Subject } from &quot;./subject.interface&quot;;

export class ConcreteObserverB implements Observer {
  public update(subject: Subject): void {
    if (
      subject instanceof ConcreteSubject &amp;&amp;
      (subject.state === 0 || subject.state &gt;= 2)
    ) {
      console.log(&quot;ConcreteObserverB: Reacted to the event.&quot;);
    }
  }
}
</code></pre>
<p>Finally, we define our <code>Client</code> or <code>Context</code> class, which makes use of this pattern. In the following code the necessary classes to simulate the use of <code>Subject</code> and <code>Observer</code> are implemented:</p>
<pre><code class="language-javascript">import { ConcreteObserverA } from &quot;./concrete-observerA&quot;;
import { ConcreteObserverB } from &quot;./concrete-observerB&quot;;
import { ConcreteSubject } from &quot;./concrete-subject&quot;;

const subject = new ConcreteSubject();

const observer1 = new ConcreteObserverA();
subject.attach(observer1);

const observer2 = new ConcreteObserverB();
subject.attach(observer2);

subject.operation();
subject.operation();

subject.detach(observer2);

subject.operation();
</code></pre>
<hr>
<h2 id="example2auctionsusingobserver">Example 2 — Auctions using Observer</h2>
<p>In this example we're going to use the <em>Observer</em> pattern to simulate an action house in which a group of auctioneers (<code>Auctioneer</code>) bid for different products (<code>product</code>). The auction is directed by an agent (<code>Agent</code>). All of our auctioneers need to be notified each time one of them increases their bid, so that they can decide whether to continue bidding or to retire.</p>
<p>Like we did in the previous example, let's begin by taking a look at the UML diagram that is going to help us identify each of the parts that this pattern is composed of.</p>
<p><img src="https://cdn-images-1.medium.com/max/2402/1*4EraBmYxYAQlQH_PRXb7VA.jpeg" alt="Understanding the Observer Design Patterns"></p>
<p>The <code>product</code> that is being auctioned is the <code>Subject</code>'s state, and all of the <code>observer</code>s await notifications whenever it changes. Therefore, the <code>product</code> class is comprised of three attributes: <code>price</code>, <code>name</code> and <code>auctioneer</code> (the auctioneer that is assigned the product).</p>
<pre><code class="language-javascript">import { Auctioneer } from &quot;./auctioneer.interface&quot;;

export class Product {
  public price;
  public name;
  public auctionner: Auctioneer = null;

  constructor(product) {
    this.price = product.price || 10;
    this.name = product.name || &quot;Unknown&quot;;
  }
}
</code></pre>
<p>The <code>Agent</code> is the interface that defines the methods for managing the group of  <code>Auctioneer</code>s, and notifying them that the bid on the auctioned product has changed. In this case, the <code>attach</code> and <code>detach</code> methods have been renamed to <code>subscribe</code> and <code>unsubscribe</code>.</p>
<pre><code class="language-javascript">import { Auctioneer } from &quot;./auctioneer.interface&quot;;

export interface Agent {
  subscribe(auctioneer: Auctioneer): void;
  unsubscribe(auctioneer: Auctioneer): void;
  notify(): void;
}
</code></pre>
<p>The concrete implementation of the <code>Agent</code> interface is performed by the <code>ConcreteAgent</code> class. As well as the three methods previously described, which have a very similar behavior to the one presented in the previous example, the <code>bidUp</code> method has been implemented, which, after making some checks on the auctioneer's bid, assigns it as valid and notifies all of the auctioneers of the change.</p>
<pre><code class="language-javascript">import { Agent } from &quot;./agent.interface&quot;;
import { Auctioneer } from &quot;./auctioneer.interface&quot;;
import { Product } from &quot;./product.model&quot;;

export class ConcreteAgent implements Agent {
  public product: Product;
  private auctioneers: Auctioneer[] = [];

  public subscribe(auctioneer: Auctioneer): void {
    const isExist = this.auctioneers.includes(auctioneer);
    if (isExist) {
      return console.log(&quot;Agent: Auctioneer has been attached already.&quot;);
    }

    console.log(&quot;Agent: Attached an auctioneer.&quot;);
    this.auctioneers.push(auctioneer);
  }

  public unsubscribe(auctioneer: Auctioneer): void {
    const auctioneerIndex = this.auctioneers.indexOf(auctioneer);
    if (auctioneerIndex === -1) {
      return console.log(&quot;Agent: Nonexistent auctioneer.&quot;);
    }

    this.auctioneers.splice(auctioneerIndex, 1);
    console.log(&quot;Agent: Detached an auctioneer.&quot;);
  }

  public notify(): void {
    console.log(&quot;Agent: Notifying auctioneer...&quot;);
    for (const auctioneer of this.auctioneers) {
      auctioneer.update(this);
    }
  }

  public bidUp(auctioneer: Auctioneer, bid: number): void {
    console.log(&quot;Agent: I'm doing something important.&quot;);
    const isExist = this.auctioneers.includes(auctioneer);
    if (!isExist) {
      return console.log(&quot;Agent: Auctioneer there is not in the system.&quot;);
    }
    if (this.product.price &gt;= bid) {
      console.log(&quot;bid&quot;, bid);
      console.log(&quot;price&quot;, this.product.price);
      return console.log(`Agent: ${auctioneer.name}, your bid is not valid`);
    }
    this.product.price = bid;
    this.product.auctionner = auctioneer;

    console.log(
      `Agent: The new price is ${bid} and the new owner is ${auctioneer.name}`
    );
    this.notify();
  }
}
</code></pre>
<p>In this problem there are four different types of <code>Auctioneer</code> defined in the <code>AuctioneerA</code>, <code>AuctioneerB</code>, <code>AuctioneerC</code> and <code>AuctioneerD</code> classes. All of these auctioneers implement the <code>Auctioneer</code> interface, which defines the <code>name</code>, <code>MAX_LIMIT</code> and the <code>update</code> method. The <code>MAX_LIMIT</code> attribute defines the maximum amount that can be bid by each type of <code>Auctioneer</code>.</p>
<pre><code class="language-javascript">import { Agent } from &quot;./agent.interface&quot;;

export interface Auctioneer {
  name: string;
  MAX_LIMIT: number;
  update(agent: Agent): void;
}
</code></pre>
<p>The different types of <code>Auctioneer</code> have been defined, to illustrate that each one will have a different behavior upon receiving the <code>Agent</code>s notification in the <code>update</code> method. Nevertheless, all that has been modified in this example is the probability of continuing to bid and the amount they increase their bids by.</p>
<pre><code class="language-javascript">import { Agent } from &quot;./agent.interface&quot;;
import { Auctioneer } from &quot;./auctioneer.interface&quot;;
import { ConcreteAgent } from &quot;./concrete-agent&quot;;

export class ConcreteAuctioneerA implements Auctioneer {
  name = &quot;ConcreteAuctioneerA&quot;;
  MAX_LIMIT = 100;

  public update(agent: Agent): void {
    if (!(agent instanceof ConcreteAgent)) {
      throw new Error(&quot;ERROR: Agent is not a ConcreteAgent&quot;);
    }

    if (agent.product.auctionner === this) {
      return console.log(`${this.name}: I'm the owner... I'm waiting`);
    }

    console.log(`${this.name}: I am not the owner... I'm thinking`);
    const bid = Math.round(agent.product.price * 1.1);
    if (bid &gt; this.MAX_LIMIT) {
      return console.log(`${this.name}: The bid is higher than my limit.`);
    }
    agent.bidUp(this, bid);
  }
}
</code></pre>
<pre><code class="language-javascript">import { Agent } from &quot;./agent.interface&quot;;
import { Auctioneer } from &quot;./auctioneer.interface&quot;;
import { ConcreteAgent } from &quot;./concrete-agent&quot;;

export class ConcreteAuctioneerB implements Auctioneer {
  name = &quot;ConcreteAuctioneerB&quot;;
  MAX_LIMIT = 200;

  public update(agent: Agent): void {
    if (!(agent instanceof ConcreteAgent)) {
      throw new Error(&quot;ERROR: Agent is not a ConcreteAgent&quot;);
    }

    if (agent.product.auctionner === this) {
      return console.log(`${this.name}: I'm the owner... I'm waiting`);
    }

    console.log(`${this.name}: I am not the owner... I'm thinking`);
    const isBid = Math.random() &lt; 0.5;
    if (!isBid) {
      return console.log(`${this.name}: I give up!`);
    }
    const bid = Math.round(agent.product.price * 1.05);
    if (bid &gt; this.MAX_LIMIT) {
      return console.log(`${this.name}: The bid is higher than my limit.`);
    }
    agent.bidUp(this, bid);
  }
}
</code></pre>
<pre><code class="language-javascript">import { Agent } from &quot;./agent.interface&quot;;
import { Auctioneer } from &quot;./auctioneer.interface&quot;;
import { ConcreteAgent } from &quot;./concrete-agent&quot;;

export class ConcreteAuctioneerC implements Auctioneer {
  name = &quot;ConcreteAuctioneerC&quot;;
  MAX_LIMIT = 500;

  public update(agent: Agent): void {
    if (!(agent instanceof ConcreteAgent)) {
      throw new Error(&quot;ERROR: Agent is not a ConcreteAgent&quot;);
    }

    if (agent.product.auctionner === this) {
      return console.log(`${this.name}: I'm the owner... I'm waiting`);
    }

    console.log(`${this.name}: I am not the owner... I'm thinking`);
    const isBid = Math.random() &lt; 0.2;
    if (!isBid) {
      return console.log(`${this.name}: I give up!`);
    }
    const bid = Math.round(agent.product.price * 1.3);
    if (bid &gt; this.MAX_LIMIT) {
      return console.log(`${this.name}: The bid is higher than my limit.`);
    }
    agent.bidUp(this, bid);
  }
}
</code></pre>
<pre><code class="language-javascript">import { Agent } from &quot;./agent.interface&quot;;
import { Auctioneer } from &quot;./auctioneer.interface&quot;;
import { ConcreteAgent } from &quot;./concrete-agent&quot;;

export class ConcreteAuctioneerD implements Auctioneer {
  name = &quot;ConcreteAuctioneerD&quot;;
  MAX_LIMIT = 1000;

  public update(agent: Agent): void {
    if (!(agent instanceof ConcreteAgent)) {
      throw new Error(&quot;ERROR: Agent is not a ConcreteAgent&quot;);
    }

    if (agent.product.auctionner === this) {
      return console.log(`${this.name}: I'm the owner... I'm waiting`);
    }

    console.log(`${this.name}: I am not the owner... I'm thinking`);
    const isBid = Math.random() &lt; 0.8;
    if (!isBid) {
      return console.log(`${this.name}: I give up!`);
    }
    const bid = Math.round(agent.product.price * 1.2);
    if (bid &gt; this.MAX_LIMIT) {
      return console.log(`${this.name}: The bid is higher than my limit.`);
    }
    agent.bidUp(this, bid);
  }
}
</code></pre>
<p>Finally, let's show the <code>Client</code> class, which makes use of the <em>observer</em> pattern. In this example, an auction house is declared, with an <code>Agent</code> and four <code>Auctioneer</code>s, where two different products (<code>diamond</code> and <code>gem</code>) are being auctioned. In the first auction, all four auctioneers participate. In the second auction, the <code>D</code> class auctioneer retires leaving the three remaining to participate.</p>
<pre><code class="language-javascript">import { ConcreteAgent } from &quot;./concrete-agent&quot;;
import { ConcreteAuctioneerA } from &quot;./concrete-auctioneerA&quot;;
import { ConcreteAuctioneerB } from &quot;./concrete-auctioneerB&quot;;
import { ConcreteAuctioneerC } from &quot;./concrete-auctioneerC&quot;;
import { ConcreteAuctioneerD } from &quot;./concrete-auctioneerD&quot;;
import { Product } from &quot;./product.model&quot;;

const concreteAgent = new ConcreteAgent();

const auctioneerA = new ConcreteAuctioneerA();
const auctioneerB = new ConcreteAuctioneerB();
const auctioneerC = new ConcreteAuctioneerC();
const auctioneerD = new ConcreteAuctioneerD();

concreteAgent.subscribe(auctioneerA);
concreteAgent.subscribe(auctioneerB);
concreteAgent.subscribe(auctioneerC);
concreteAgent.subscribe(auctioneerD);

const diamond = new Product({ name: &quot;Diamond&quot;, price: 5 });
concreteAgent.product = diamond;

concreteAgent.bidUp(auctioneerA, 10);

console.log(&quot;--------- new Bid-----------&quot;);

concreteAgent.unsubscribe(auctioneerD);

const gem = new Product({ name: &quot;Gem&quot;, price: 3 });
concreteAgent.product = gem;

concreteAgent.bidUp(auctioneerB, 5);

console.log(`The winner of the bid is 
             Product: ${diamond.name}
             Name: ${diamond.auctionner.name}
             Price: ${diamond.price}`);

console.log(`The winner of the bid is 
             Product: ${gem.name}
             Name: ${gem.auctionner.name}
             Price: ${gem.price}`);
</code></pre>
<p>Finally, I've created <code>two npm scripts</code>, through which the code presented in this article can be executed:</p>
<pre><code class="language-javascript">npm run example1
npm run example2
</code></pre>
<p>GitHub Repo available <a href="https://github.com/Caballerog/blog/tree/master/observer-pattern">here.</a></p>
<hr>
<h1 id="conclusion">Conclusion</h1>
<p><em><strong>Observer</strong></em> is a design pattern that allows respecting the <em>Open-Closed Principle</em> since new <code>Subject</code> and <code>Observer</code> can be created without breaking the existing code. In addition, it allows communication between two actors of the system without the need for them to be linked in the knowledge of each other. Finally, the performance degradation that occurs in more elementary techniques such as busy-waiting and polling is overcome.</p>
<p>Finally, the most important thing about this pattern is not the concrete implementation of it, but being able to recognize the problem that this pattern can solve, and when it can be applied. The specific implementation is the least of it, since it will vary depending on the programming language used.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Understanding the Abstract Factory Design Patterns]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>There are 23 classic design patterns which are described in the original book Design Patterns: Elements of Reusable Object-Oriented Software. These patterns provide solutions to particular problems often repeated in software development.</p>
<p>In this article, I am going to describe how the <strong>Abstract-Factory Pattern</strong> works and when it should be</p>]]></description><link>https://www.carloscaballero.io/understanding-the-abstract-factory-design-patterns/</link><guid isPermaLink="false">5ff0574b886c5e00010dff4c</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[NestJS]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Carlos Caballero]]></dc:creator><pubDate>Sun, 28 Feb 2021 19:35:03 GMT</pubDate><media:content url="http://www.carloscaballero.io/content/images/2021/01/0_xmzm0tpbHPidsTWY.jpeg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><img src="http://www.carloscaballero.io/content/images/2021/01/0_xmzm0tpbHPidsTWY.jpeg" alt="Understanding the Abstract Factory Design Patterns"><p>There are 23 classic design patterns which are described in the original book Design Patterns: Elements of Reusable Object-Oriented Software. These patterns provide solutions to particular problems often repeated in software development.</p>
<p>In this article, I am going to describe how the <strong>Abstract-Factory Pattern</strong> works and when it should be applied.</p>
<p>--</p>
<h1 id="abstractfactorybasicidea">Abstract Factory: Basic Idea</h1>
<p>Wikipedia provides us with the following definition:</p>
<blockquote>
<p>The <a href="https://en.wikipedia.org/wiki/Software_design_pattern"><strong>abstract factory pattern</strong></a> provides a way to encapsulate a group of individual <a href="https://en.wikipedia.org/wiki/Factory_object">factories</a> that have a common theme without specifying their concrete classes — <a href="https://en.wikipedia.org/wiki/Factory_method_pattern">Wikipedia</a></p>
</blockquote>
<p>On the other hand, the definition provided by the original book is the following:</p>
<blockquote>
<p>Provide an interface for creating families of related or dependent objects without specifying their concrete classes — Design Patterns: Elements of Reusable Object-Oriented Software</p>
</blockquote>
<p>On many occasions, we need to create different types of objects that are not known a priori from a list of possible objects in which these objects are related in the creation process. The natural tendency is to create a <code>factoryManager</code> class that allows us to obtain the different types of objects based on a parameter. However, this solution has two serious drawbacks that we will describe throughout this article:</p>
<ol>
<li>
<p>It breaks the principle of <em>Open-Closed Principle</em> which gives code that is not clean; and that it is not easy to maintain when the software scales.</p>
</li>
<li>
<p>The <code>factoryManager</code> class is attached to all types of objects that you want to build, creating code known as spaghetti code.</p>
</li>
</ol>
<p>This problem and its solution have been dealt with in the article in which the <strong>Factory-Method</strong> design pattern is presented, which allows solving this problem when the creation of objects is simple and they are not related to each other. Therefore, it is recommended that you read this article first to later address this <strong>AbstractFactory</strong> pattern.</p>
<p>The <strong>Abstract Factory</strong> pattern allows for a clearer code, since it avoids the previously mentioned problem. The UML diagram of this pattern is as follows:</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*Hq1dVINI67d-_IQjco5-Sw.png" alt="Understanding the Abstract Factory Design Patterns"></p>
<p>The classes that comprise this pattern are the following:</p>
<ul>
<li>
<p><strong>AbstractProductA</strong> and <strong>AbstractProductB</strong> are the interfaces for a set of products of the same type but of a different family. In other words, all the products that implement the <code>AbstractProductA</code> class belong to the same product type, although they will be organized into different families. This type of object will be better understood in the concrete example that follows.</p>
</li>
<li>
<p><strong>ProductA1</strong>, <strong>ProductA2</strong>, <strong>ProductB1</strong> and <strong>ProductB</strong> are concrete implementations of each type of <code>AbstractProduct</code>.</p>
</li>
<li>
<p><strong>AbstractFactory</strong> is the interface that declares the set of creation methods for each of the concrete factories (<code>ConcreteFactory1</code> and <code>ConcreteFactory2</code>).</p>
</li>
<li>
<p><strong>ConcreteFactory1</strong> and <strong>ConcreteFactory2</strong> implement the creation methods of the <code>AbstractFactory</code> class for each of the product families.</p>
</li>
</ul>
<hr>
<h1 id="abstractfactorypatternwhentouse">Abstract Factory Pattern: When To Use</h1>
<ol>
<li>
<p>The problems solved by <strong>Abstract Factory</strong> are similar to those solved by the <strong>Factory-Method</strong> pattern, but with greater abstraction in the types of objects that need to be created. Therefore, in the case of <strong>Abstract Factory</strong> it is required to work with several families of products related to each other rather than in a set of products.</p>
</li>
<li>
<p><strong>The family of objects with which the client must work is not known a priori</strong>. Rather, this knowledge depends directly on the interaction of another user with the system (end user or system).</p>
</li>
<li>
<p>In the event that it is <strong>necessary to extend the internal components</strong> (the number of families and objects that are created) without having to have the code coupled, but rather have interfaces and abstractions that allow to easily extend with factories and specific products.</p>
</li>
</ol>
<hr>
<h1 id="abstractfactorypatternadvantagesanddisadvantages">Abstract Factory Pattern: Advantages and Disadvantages</h1>
<p>The <em>Abstract Factory</em> pattern has a number of advantages that can be summarized in the following points:</p>
<ul>
<li>
<p>Compatibility between products created by the same <em>factory</em> class is guaranteed.</p>
</li>
<li>
<p><strong>Clean code</strong> as the <em>Open-Closed Principle</em> is guaranteed since new product families can be introduced without breaking the existing code.</p>
</li>
<li>
<p><strong>Cleaner code</strong> since the <em>Single Responsibility Principle (SRP)</em> is respected since the responsibility of creating the concrete product is transferred to the concrete creator class instead of the client class having this responsibility.</p>
</li>
<li>
<p><strong>Cleaner code</strong> because the <em>Single Responsibility Principle (SRP)</em> is respected since the responsibility of creating the concrete product is transferred to the concrete creator class instead of the client class having this responsibility.</p>
</li>
</ul>
<p>However, the main drawback of the <em>abstract factory</em> pattern, like most design patterns, is that there is an increase in complexity in the code, and an increase in the number of classes required for the code. Although, this disadvantage is well known when applying design patterns for it is the price to pay for gaining abstraction in the code.</p>
<hr>
<h1 id="abstractfactorypatternexamples">Abstract Factory Pattern Examples</h1>
<p>Next, we are going to illustrate two examples of application of the <em>Abstract Factory</em> pattern:</p>
<ol>
<li>
<p>Basic structure of the <strong>Abstract Factory</strong> pattern. In this example we are going to translate the theoretical UML diagram into TypeScript code to identify each of the classes involved in the pattern.</p>
</li>
<li>
<p>Creation of <strong>characters in a video game</strong>. Let's think of the classic WoW (<em>World of Warcraft</em>) in which the player can have a set of objects depending on the race they choose. For example, we will have the races: Humans, Orcs and Magicians; which will have weapons and armor (products) that will be different depending on the race (the family of objects).</p>
</li>
</ol>
<p>The following examples will show the implementation of this pattern using <strong>TypeScript</strong>. We have chosen TypeScript to carry out this implementation rather than JavaScript — the latter lacks interfaces or abstract classes so the responsibility of implementing both the interface and the abstract class would fall on the developer.</p>
<h1 id="example1basicstructureoftheabstractfactorypattern">Example 1: Basic structure of the abstract factory pattern</h1>
<p>In this first example, we’re going to translate the theoretical UML diagram into TypeScript to test the potential of this pattern. This is the diagram to be implemented:</p>
<p><img src="https://cdn-images-1.medium.com/max/2646/1*4kc8r8jedSbJ6JDo1vkI4g.jpeg" alt="Understanding the Abstract Factory Design Patterns"></p>
<p>First, we are going to define the interfaces (<code>AbstractProductA</code> and <code>AbstractProductB</code>) that define the types of concrete products that we want to create for the different families. In our concrete example, to simplify the understanding of the pattern as much as possible, only one method has been defined for each of these interfaces: <code>usefulFunctionA</code> and <code>usefulFunctionB</code> respectively.</p>
<pre><code class="language-javascript">export interface AbstractProductA {
  usefulFunctionA(): string;
}
</code></pre>
<pre><code class="language-javascript">export interface AbstractProductB {
  usefulFunctionB(): string;
}
</code></pre>
<p>The next step is to define the specific products that implement each of these interfaces. In our case, two concrete objects will be implemented for each of these abstract classes. For the first interface (<code>AbstractProductA</code>) the classes<code> ConcreteProductA1</code> and <code>ConcreteProductA2</code> are implemented, while for the second interface (<code>AbstractProductB</code>) the classes <code>ConcreteProductB1</code> and <code>ConcreteProductB2</code> are implemented.</p>
<pre><code class="language-javascript">import { AbstractProductA } from &quot;./abstract-productA&quot;;

export class ConcreteProductA1 implements AbstractProductA {
  public usefulFunctionA(): string {
    return &quot;The result of the product A1.&quot;;
  }
}
</code></pre>
<pre><code class="language-javascript">import { AbstractProductA } from &quot;./abstract-productA&quot;;

export class ConcreteProductA2 implements AbstractProductA {
  public usefulFunctionA(): string {
    return &quot;The result of the product A2.&quot;;
  }
}
</code></pre>
<pre><code class="language-javascript">import { AbstractProductB } from &quot;./abstract-productB&quot;;

export class ConcreteProductB1 implements AbstractProductB {
  public usefulFunctionB(): string {
    return &quot;The result of the product B1.&quot;;
  }
}
</code></pre>
<pre><code class="language-javascript">import { AbstractProductB } from &quot;./abstract-productB&quot;;

export class ConcreteProductB2 implements AbstractProductB {
  public usefulFunctionB(): string {
    return &quot;The result of the product B2.&quot;;
  }
}
</code></pre>
<p>Once the structure of classes related to the creation of products has been defined, we proceed to define the structure of classes related to the creation of factories in charge of creating these objects. Therefore, first the abstract class <code>AbstractFactory</code> is defined in which the methods in charge of creating the concrete objects by the concrete factories are defined. However, note that these methods return the abstract classes from each of the <code>AbstractProductA</code> and<code> AbstractProductB</code> products.</p>
<pre><code class="language-javascript">import { AbstractProductA } from &quot;./abstract-productA&quot;;
import { AbstractProductB } from &quot;./abstract-productB&quot;;

export interface AbstractFactory {
  createProductA(): AbstractProductA;
  createProductB(): AbstractProductB;
}
</code></pre>
<p>Finally, it would be necessary to define the concrete factories, in which the concrete classes are instantiated. In this first example, the <code>ConcreteFactory1</code> factory will be in charge of instantiating the concrete objects of family 1 (<code>ConcreteProductA1</code> and <code>ConcreteProductB1</code>) and the <code>ConcreteFactory2</code> factory will be in charge of instantiating the concrete objects of family 2 (<code>ConcreteProductA2</code> and <code>ConcreteProductB2</code>).</p>
<pre><code class="language-javascript">import { AbstractFactory } from &quot;./abstract-factory&quot;;
import { AbstractProductA } from &quot;./abstract-productA&quot;;
import { AbstractProductB } from &quot;./abstract-productB&quot;;
import { ConcreteProductA1 } from &quot;./concrete-productA1&quot;;
import { ConcreteProductB1 } from &quot;./concrete-productB1&quot;;

export class ConcreteFactory1 implements AbstractFactory {
  public createProductA(): AbstractProductA {
    return new ConcreteProductA1();
  }

  public createProductB(): AbstractProductB {
    return new ConcreteProductB1();
  }
}
</code></pre>
<pre><code class="language-javascript">import { AbstractFactory } from &quot;./abstract-factory&quot;;
import { AbstractProductA } from &quot;./abstract-productA&quot;;
import { AbstractProductB } from &quot;./abstract-productB&quot;;
import { ConcreteProductA2 } from &quot;./concrete-productA2&quot;;
import { ConcreteProductB2 } from &quot;./concrete-productB2&quot;;

export class ConcreteFactory2 implements AbstractFactory {
  public createProductA(): AbstractProductA {
    return new ConcreteProductA2();
  }

  public createProductB(): AbstractProductB {
    return new ConcreteProductB2();
  }
}
</code></pre>
<p>Although it is not a direct part of the pattern, it would be necessary to see the execution of the pattern by the <code>Client/Context</code> class. In this case, the <code>ClientCode</code> method does not need to know the specific factory to create the products, but receiving an object of the <code>AbstractFactory</code> class as a parameter is sufficient to execute the <code>CreateProductA</code> and <code>CreateProductB</code> methods.</p>
<pre><code class="language-javascript">import { AbstractFactory } from &quot;./abstract-factory&quot;;
import { ConcreteFactory1 } from &quot;./concrete-factory1&quot;;
import { ConcreteFactory2 } from &quot;./concrete-factory2&quot;;

function clientCode(factory: AbstractFactory) {
  const productA = factory.createProductA();
  const productB = factory.createProductB();

  console.log(productA.usefulFunctionA());
  console.log(productB.usefulFunctionB());
}

console.log(&quot;Client: Testing client code with ConcreteFactory1&quot;);
clientCode(new ConcreteFactory1());

console.log(&quot;----------------&quot;);

console.log(&quot;Client: Testing the same client code with ConcreteFactory2&quot;);
clientCode(new ConcreteFactory2());
</code></pre>
<hr>
<h1 id="example2creationofheroesequipmentofavideogame">Example 2 - Creation of Heroes equipment of a video game</h1>
<p>We have already seen the theoretical example of this pattern, so you already understand the responsibilities of each of the classes of this pattern. Now, we are going to illustrate a real example in which we will identify each of the classes of this design pattern.</p>
<p>Our problem consists of the representation of the equipment of different heroes or characters in a video game. We will focus on the classic WoW video game (<em>World of Warcraft</em>), in which the heroes are divided into three races: Humans, orcs and wizards. Each of these heroes can have different armor (<code>armor</code>) and weapons (<code>weapon</code>) that vary depending on the race. Therefore, we can already identify that the products to be built will be the different types of armor and weapons, and the product families are the product family for a human, orc and wizard.</p>
<p>Therefore, following the same methodology as the one we have presented in the previous examples, we are going to start by looking at the UML diagram that will help us identify each of the parts of this pattern.</p>
<p><img src="https://cdn-images-1.medium.com/max/3298/1*2bsCUIHyKdpbarsKMWtF4w.jpeg" alt="Understanding the Abstract Factory Design Patterns"></p>
<p>A priori, the class design of this problem may be impressive, but if we have understood the example of the basic structure of this pattern, we will understand this example perfectly.</p>
<p>We will start by creating each of the specific product types. That is, the first thing that is defined is the interface that models a weapon (<code>weapon</code>).</p>
<pre><code class="language-javascript">export interface Weapon {
  usefulFunction(): string;
}
</code></pre>
<p>To simplify the example, only one method called <code>usefulFunction</code> has been defined for each one of the <code>weapons</code>. Thus, the specific weapons that are defined are <code>sword</code>, <code>axe</code> and <code>mage-fireball</code>.</p>
<pre><code class="language-javascript">import { Weapon } from &quot;./weapon.interface&quot;;

export class Sword implements Weapon {
  public usefulFunction(): string {
    return &quot;The result of the Sword&quot;;
  }
}
</code></pre>
<pre><code class="language-javascript">import { Weapon } from &quot;./weapon.interface&quot;;

export class Axe implements Weapon {
  public usefulFunction(): string {
    return &quot;The result of the Axe&quot;;
  }
}
</code></pre>
<pre><code class="language-javascript">import { Weapon } from &quot;./weapon.interface&quot;;

export class MageFireball implements Weapon {
  public usefulFunction(): string {
    return &quot;The result of the MageFireball&quot;;
  }
}
</code></pre>
<p>In the same way that the <code>weapon</code> has been defined, the different armor (<code>armor</code>) is defined. In this specific case, we have created a collaboration between the armor (<code>armor</code>) and the weapon (<code>weapon</code>) through a method called <code>usefulFunctionWithWeapon</code> to illustrate that the objects can be related to each other. The most important thing to note is that the collaborator parameter is of the abstract class <code>Weapon</code>, rather than working with concrete classes.</p>
<pre><code class="language-javascript">import { Weapon } from &quot;../weapons/weapon.interface&quot;;

export interface Armor {
  usefulFunction(): string;
  usefulFunctionWithWeapon(collaborator: Weapon): string;
}
</code></pre>
<p>The specific armors that we need for our problem are <code>BodyArmor</code>,<code>OrcArmor</code> and <code>Cloak</code> that will be created by each of the object families according to the Hero's race.</p>
<pre><code class="language-javascript">import { Armor } from &quot;./armor-interface&quot;;
import { Weapon } from &quot;../weapons/weapon.interface&quot;;

export class BodyArmor implements Armor {
  public usefulFunction(): string {
    return &quot;The result of the BodyArmor&quot;;
  }

  public usefulFunctionWithWeapon(collaborator: Weapon): string {
    const result = collaborator.usefulFunction();
    return `The result of the BodyAmor collaborating with the (${result})`;
  }
}
</code></pre>
<pre><code class="language-javascript">import { Armor } from &quot;./armor-interface&quot;;
import { Weapon } from &quot;../weapons/weapon.interface&quot;;

export class OrcArmor implements Armor {
  public usefulFunction(): string {
    return &quot;The result of the OrcArmor&quot;;
  }

  public usefulFunctionWithWeapon(collaborator: Weapon): string {
    const result = collaborator.usefulFunction();
    return `The result of the OrcAmor collaborating with the (${result})`;
  }
}
</code></pre>
<pre><code class="language-javascript">import { Armor } from &quot;./armor-interface&quot;;
import { Weapon } from &quot;../weapons/weapon.interface&quot;;

export class Cloak implements Armor {
  public usefulFunction(): string {
    return &quot;The result of the Cloak&quot;;
  }

  public usefulFunctionWithWeapon(collaborator: Weapon): string {
    const result = collaborator.usefulFunction();
    return `The result of the Cloak collaborating with the (${result})`;
  }
}
</code></pre>
<p>Up to this point, the specific products that we want to create in our video game have been defined but the creation rules have not been established. It is the specific factories that will be in charge of creating the specific products according to the Hero's race. The first class to define is the abstract class <code>AbstractFactory</code> which defines the <code>createWeapon</code> and <code>createAmor</code> methods that are responsible for creating the abstract <code>Weapon</code> and <code>Armor</code> products. Notice that all the code up to this point has made use of abstract classes.</p>
<pre><code class="language-javascript">import { Armor } from &quot;./armor/armor-interface&quot;;
import { Weapon } from &quot;./weapons/weapon.interface&quot;;

export interface AbstractFactory {
  createWeapon(): Weapon;
  createArmor(): Armor;
}
</code></pre>
<p>At this time, we have to implement the concrete factories <code>HumanFactory</code>, <code>OrcFactory</code> and <code>MageFactory</code> in which the creator methods are implemented with the concrete products based on the race of the hero.</p>
<pre><code class="language-javascript">import { AbstractFactory } from &quot;./abstract-factory&quot;;
import { Armor } from &quot;./armor/armor-interface&quot;;
import { BodyArmor } from &quot;./armor/body-armor.model&quot;;
import { Sword } from &quot;./weapons/sword.model&quot;;
import { Weapon } from &quot;./weapons/weapon.interface&quot;;

export class WarriorFactory implements AbstractFactory {
  public createWeapon(): Weapon {
    return new Sword();
  }

  public createArmor(): Armor {
    return new BodyArmor();
  }
}
</code></pre>
<pre><code class="language-javascript">import { AbstractFactory } from &quot;./abstract-factory&quot;;
import { Armor } from &quot;./armor/armor-interface&quot;;
import { Axe } from &quot;./weapons/axe.model&quot;;
import { OrcArmor } from &quot;./armor/orc-armor.model&quot;;
import { Weapon } from &quot;./weapons/weapon.interface&quot;;

export class OrcFactory implements AbstractFactory {
  public createWeapon(): Weapon {
    return new Axe();
  }

  public createArmor(): Armor {
    return new OrcArmor();
  }
}
</code></pre>
<pre><code class="language-javascript">import { AbstractFactory } from &quot;./abstract-factory&quot;;
import { Armor } from &quot;./armor/armor-interface&quot;;
import { Cloak } from &quot;./armor/cloak.model&quot;;
import { MageFireball } from &quot;./weapons/mage-fireball.model&quot;;
import { Weapon } from &quot;./weapons/weapon.interface&quot;;

export class MageFactory implements AbstractFactory {
  public createWeapon(): Weapon {
    return new MageFireball();
  }

  public createArmor(): Armor {
    return new Cloak();
  }
}
</code></pre>
<p>To conclude the example of creating the equipment of our heroes, we are going to implement the <code>Client/Context</code> class.</p>
<pre><code class="language-javascript">import { AbstractFactory } from &quot;./abstract-factory&quot;;
import { MageFactory } from &quot;./mage-factory&quot;;
import { OrcFactory } from &quot;./orc-factory&quot;;
import { WarriorFactory } from &quot;./warrior-factory&quot;;

function clientCode(factory: AbstractFactory) {
  const sword = factory.createWeapon();
  const armor = factory.createArmor();

  console.log(armor.usefulFunction());
  console.log(armor.usefulFunctionWithWeapon(sword));
}

console.log(&quot;Client: WarriorFactory&quot;);
clientCode(new WarriorFactory());

console.log(&quot;----------------&quot;);

console.log(&quot;Client: OrcFactory&quot;);
clientCode(new OrcFactory());

console.log(&quot;----------------&quot;);

console.log(&quot;Client: MageFactory&quot;);
clientCode(new MageFactory());
</code></pre>
<p>Finally, I’ve created two <code>npm scripts</code>, through which the code presented in this article can be executed:</p>
<pre><code class="language-javascript">    npm run example1
    npm run example2
</code></pre>
<p>GitHub Repo available <a href="https://github.com/Caballerog/blog/tree/master/abstract-factory-pattern">here</a>.</p>
<h1 id="conclusion">Conclusion</h1>
<p><strong>Abstract Factory</strong> is a design pattern that allows respecting the <em>Open-Closed Principle</em> principle and delegates the responsibility for creating objects to specific classes (concrete factories) using polymorphism. This allows us to have a much cleaner and more scalable code.</p>
<p>This pattern solves the problem that arises when it is necessary to create different types of objects that depend on the interaction of a client with the system in which it is not known beforehand which object the client will create. Furthermore, these objects are related by object families, in such a way that it allows to have them separated by context or object types when using different factories.</p>
<p>Another advantage of this pattern is that the system is not coupled to a set of concrete classes, but the client only communicates with abstract classes allowing to have a much more maintainable code when the software scales.</p>
<p>Finally, the most important thing about this pattern is not the concrete implementation of it, but being able to recognize the problem that this pattern can solve, and when it can be applied. The specific implementation is the least of it, since it will vary depending on the programming language used.</p>
<!--kg-card-end: markdown--><p></p>]]></content:encoded></item><item><title><![CDATA[ES2021 Features in simple examples]]></title><description><![CDATA[<!--kg-card-begin: markdown--><hr>
<p>In this series, we are going to show the EcmaScript features from 2015 to today.</p>
<ul>
<li>ES2015 aka ES6</li>
<li><a href="https://www.carloscaballero.io/javascript-es2016-features-with-examples/">ES2016 aka ES7</a></li>
<li><a href="https://www.carloscaballero.io/javascript-es2017-features-with-simple-examples/">ES2017 aka ES8</a></li>
<li><a href="https://www.carloscaballero.io/javascript-es2018-features-with-simple-examples/">ES2018 aka ES9</a></li>
<li><a href="https://carloscaballero.io/12-es10-features-in-12-simple-examples/">ES2019 aka ES10</a></li>
<li><a href="https://carloscaballero.io/es2020-features-in-simple-examples">ES2020 aka ES11</a></li>
<li><a href="https://carloscaballero.io/es2021-features-in-simple-examples">ES2021 aka ES12</a></li>
</ul>
<hr>
<h1 id="introduction">Introduction</h1>
<p>ES2021 is the version of ECMAScript corresponding to the year 2021. This version</p>]]></description><link>https://www.carloscaballero.io/es2021-features-in-simple-examples/</link><guid isPermaLink="false">5fdf3d99886c5e00010dfc83</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Carlos Caballero]]></dc:creator><pubDate>Sat, 02 Jan 2021 11:08:58 GMT</pubDate><media:content url="http://www.carloscaballero.io/content/images/2020/12/waldemar-brandt-oWUx0ON3EVc-unsplash.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><hr>
<img src="http://www.carloscaballero.io/content/images/2020/12/waldemar-brandt-oWUx0ON3EVc-unsplash.jpg" alt="ES2021 Features in simple examples"><p>In this series, we are going to show the EcmaScript features from 2015 to today.</p>
<ul>
<li>ES2015 aka ES6</li>
<li><a href="https://www.carloscaballero.io/javascript-es2016-features-with-examples/">ES2016 aka ES7</a></li>
<li><a href="https://www.carloscaballero.io/javascript-es2017-features-with-simple-examples/">ES2017 aka ES8</a></li>
<li><a href="https://www.carloscaballero.io/javascript-es2018-features-with-simple-examples/">ES2018 aka ES9</a></li>
<li><a href="https://carloscaballero.io/12-es10-features-in-12-simple-examples/">ES2019 aka ES10</a></li>
<li><a href="https://carloscaballero.io/es2020-features-in-simple-examples">ES2020 aka ES11</a></li>
<li><a href="https://carloscaballero.io/es2021-features-in-simple-examples">ES2021 aka ES12</a></li>
</ul>
<hr>
<h1 id="introduction">Introduction</h1>
<p>ES2021 is the version of ECMAScript corresponding to the year 2021. This version doesn’t include as many new features as those that appeared in ES6 (2015). However, some useful features have been incorporated.</p>
<p>This article introduces the features provided by ES2021 in easy code examples. In this way, you can quickly understand the new features without the need for a complex explanation.</p>
<p>Of course, it’s necessary to have a basic knowledge of JavaScript to fully understand the best ones introduced.</p>
<p>The new JavaScript <strong>features in ES2021</strong> are:</p>
<p>➡️ String.prototype.replaceAll<br>
➡️ Promise.any<br>
➡️ WeakRef<br>
➡️ Logical Assignment Operators<br>
➡️ Numeric separators</p>
<hr>
<h2 id="stringprotypereplaceall">String.protype.replaceAll</h2>
<p>Currently there is no way to replace all instances of a substring in a string without use of a global regexp (/regexp/g).</p>
<pre><code class="language-javascript">const fruits = '🍎+🍐+🍓+';
const fruitsWithBanana = fruits.replace(/\+/g, '🍌');
console.log(fruitsWithBanana); //🍎🍌🍐🍌🍓🍌
</code></pre>
<p>A new replaceAll method has been added to the String prototype.</p>
<pre><code class="language-javascript">const fruits = '🍎+🍐+🍓+';
const fruitsWithBanana = fruits.replaceAll('+', '🍌');
console.log(fruitsWithBanana); //🍎🍌🍐🍌🍓🍌
</code></pre>
<hr>
<h1 id="promiseany">Promise.any</h1>
<p>Promise.any gives you a signal as soon as one of the promises fulfills. This is similar to Pormise.race , except any doesn’t reject early when one of the promises rejects.</p>
<pre><code class="language-javascript">const myFetch = url =&gt; setTimeout(() =&gt; fetch(url), Math.floor(Math.random() * 3000));

const promises = [
   myFetch('/endpoint-1'),
   myFetch('/endpoint-2'),
   myFetch('/endpoint-3'),
];

// Using .then .catch
Promise.any(promises) // Any of the promises was fulfilled.
       .then(console.log) // e.g. '3'
       .catch(console.error); //All of the promises were rejected.

// Using async-await
try {
   const first = await Promise.any(promises); // Any of the promises was fulfilled.
   console.log(first);
}catch (error) { // All of the promises were rejected
   console.log(error);
}
</code></pre>
<hr>
<h2 id="weakref">WeakRef</h2>
<p>The WeakRef proposal encompasses two major new pieces of functionality:</p>
<ol>
<li>
<p>creating <em>weak references</em> to objects with the WeakRef class.</p>
</li>
<li>
<p>running user-defined <em>finalizers</em> after objects are garbage-collected, with the FinalizationRegistry class.</p>
</li>
</ol>
<p>These interfaces can be used independently or together, depending on the use case</p>
<p>A WeakRef object contains a weak reference to an object, which is called its <em>target</em> or <em>referent</em>. **A <em>weak reference <em>to an object is a reference that does not prevent the object from being reclaimed by the garbage collector.</em></em></p>
<p>A primary <strong>use for weak references is to implement caches or mappings holding large objects</strong>, where it’s desired that a large object is not kept alive solely because it appears in a cache or mapping.</p>
<pre><code class="language-javascript">function toogle(element) {
   **const weakElement = new WeakRef(element);** 
   let intervalId = null;
     
   function toggle() { 
     **const el = weakElement.deref();**
     if (!el) {
        return clearInterval(intervalId);
    }
    const decoration = weakElement.style.textDecoration;
    const style= decoration === 'none' ? 'underline' : 'none';
    decoration = style;
   }
   intervalId = setInterval(toggle, 1000);
 }

 const element = document.getElementById(&quot;link&quot;);

 toogle(element);
 setTimeout(() =&gt; element.remove(), 10000);
</code></pre>
<p><code>FinalizationRegistry</code> provides a way to request that a <em>cleanup callback</em> (<em>finalizers</em>) get called at some point when an object registered with the registry has been <em>reclaimed</em> (<code>garbage-collected</code>).</p>
<p>You create the <code>registry</code> passing in the callback:</p>
<pre><code class="language-javascript">const registry = new FinalizationRegistry(heldValue =&gt; {
  // ....
});
</code></pre>
<p>Then you <code>register</code> any objects you want a cleanup callback for by calling the register method, passing in the object and a <strong>held value</strong> for it:</p>
<pre><code class="language-javascript">registry.register(theObject, &quot;some value&quot;);
</code></pre>
<hr>
<h1 id="logicalassignmentoperators">Logical Assignment Operators</h1>
<p>Logical assignment operators combine logical operators and assignment expressions. There are two new operators:</p>
<ol>
<li><strong>Or Or Equals.</strong></li>
<li><strong>And And Equals.</strong></li>
</ol>
<pre><code class="language-javascript">// Or Or Equals
|   a   |   b   | a ||= b | a (after operation) |
| true  | true  |   true  |        true         |
| true  | false |   true  |        true         |
| false | true  |   true  |        true         |
| false | false |   false |        false        |

a ||= b
// Equivalent to:
a || (a = b);

// And And Equals
|   a   |   b   | a ||= b | a (after operation) |
| true  | true  |   true  |        true         |
| true  | false |   false |        false        |
| false | true  |   false |        false        |
| false | false |   false |        false        |

a &amp;&amp;= b
// Equivalent to:
a &amp;&amp; (a = b);
</code></pre>
<hr>
<h1 id="numericseparators">Numeric separators</h1>
<p>This feature allows that numeric literals will be more readable using a visual separation between groups of digits.</p>
<p>Using underscores (_, U+005F) as separators helps improve readability for numeric literals:</p>
<pre><code class="language-javascript">1_000_000_000           // A billion
101_475_938.38          // Hundreds of millions

const amount = 12345_00;  // 12,345 (1234500 cents, apparently)
const amount = 123_4500;  // 123.45 (4-fixed financial)
const amount = 1_234_500; // 1,234,500

0.000_001 // 1 millionth
1e10_000  // 10^10000 -- granted, far less useful / in-range...
    
const binary_literals = 0b1010_0001_1000_0101;
const hex_literals = 0xA0_B0_C0;
const bigInt_literals = 1_000_000_000_000n;
const octal_literal = 0o1234_5670;
</code></pre>
<hr>
<h1 id="conclusion">Conclusion</h1>
<p>JavaScript is a live language, and that’s something very healthy for web development. Since the appearance of ES6 in 2015, we’re living a vibrant evolution in the language. In this post, we’ve reviewed the features that arise in ES2021.</p>
<p>Although many of these features may not be essential for the development of your web application, they’re giving possibilities that could be achieved before with tricks or a lot of verbosity.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Understanding Design Patters: Factory Method]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>There are 23 classic design patterns which are described in the original book <code>Design Patterns: Elements of Reusable Object-Oriented Software</code>. These patterns provide solutions to particular problems often repeated in software development.</p>
<p>In this article, I am going to describe how the <strong>Factory-Method Pattern</strong> works and when it should be</p>]]></description><link>https://www.carloscaballero.io/understanding-design-patters-factory-method/</link><guid isPermaLink="false">5fdbdbbe886c5e00010dfc5f</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Carlos Caballero]]></dc:creator><pubDate>Wed, 30 Dec 2020 20:50:21 GMT</pubDate><media:content url="http://www.carloscaballero.io/content/images/2020/12/christopher-burns-Wiu3w-99tNg-unsplash.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><img src="http://www.carloscaballero.io/content/images/2020/12/christopher-burns-Wiu3w-99tNg-unsplash.jpg" alt="Understanding Design Patters: Factory Method"><p>There are 23 classic design patterns which are described in the original book <code>Design Patterns: Elements of Reusable Object-Oriented Software</code>. These patterns provide solutions to particular problems often repeated in software development.</p>
<p>In this article, I am going to describe how the <strong>Factory-Method Pattern</strong> works and when it should be applied.</p>
<hr>
<h1 id="factorymethodbasicidea">Factory-Method: Basic Idea</h1>
<blockquote>
<p>The <em><strong>factory method pattern</strong></em> is a <a href="https://en.wikipedia.org/wiki/Software_design_pattern">creational pattern</a> that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method — either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes — rather than by calling a constructor — <a href="https://en.wikipedia.org/wiki/Factory_method_pattern">Wikipedia</a></p>
</blockquote>
<blockquote>
<p>Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses  — Design Patterns: Elements of Reusable Object-Oriented Software</p>
</blockquote>
<p>On many occasions we need to create different types of objects that are not known a priori from a list of possible objects. The natural tendency is to create a <code>factoryManager</code> class that allows us to obtain the different types of objects based on a parameter. However, this solution has two serious drawbacks that we will describe throughout this article:</p>
<ol>
<li>
<p>It breaks the principle of <em>Open-Closed Principle</em> which leads to code that is not clean; and that it is not easy to maintain when the software scales.</p>
</li>
<li>
<p>The <code>factoryManager</code> class is attached to all types of objects that you want to build, creating code known as <code>spaghetti code</code>.</p>
</li>
</ol>
<p>The following code shows the classic problem in which there is a <code>create</code> method that returns an object of a type based on a parameter pass as an argument:</p>
<pre><code class="language-javascript">function create(type) {
  switch(type){
    case '0': return new Object1();
    case '1': return new Object2();
    case '2': return new Object3();
    default: return new Object4();
  }
}
</code></pre>
<p>The <strong>Factory-Method</strong> pattern allows for clearer code, since it avoids the problem raised above. The UML diagram of this pattern is as follows:</p>
<p><img src="https://cdn-images-1.medium.com/max/3658/1*n7p-k_qujk5DGIQhKItfww.png" alt="Understanding Design Patters: Factory Method"></p>
<p>The classes that make up this pattern are the following:</p>
<ul>
<li>
<p><strong>Product</strong> it is the common interface of all objects that can be created.</p>
</li>
<li>
<p><strong>ConcreteProductOne</strong> and <strong>ConcreteProductTwo</strong> are implementations of the <code>Product</code> interface.</p>
</li>
<li>
<p><strong>Creator</strong> is an abstract class in which the <code>factoryMethod</code> method is declared, which will be responsible for generating an object of type <code>Product</code>. The concrete implementation of the object is not carried out by this class, but responsibility is delegated to the <code>ConcreteCreator1</code> and <code>ConcreteCreator2</code> classes.</p>
</li>
<li>
<p><strong>ConcreteCreator1</strong> and <strong>ConcreteCreator2</strong> override the <code>factoryMethod</code> with the creation of the concrete object.</p>
</li>
</ul>
<p>It is important to clarify several points that are often misunderstood as a result of the name of this pattern:</p>
<ol>
<li>
<p>This pattern does not implement a <code>factory</code> method that is responsible for creating specific objects. Rather, the responsibility is delegated to the subclasses that implement the abstract class.</p>
</li>
<li>
<p>This pattern is a specific case of the <strong>[Template-Method pattern] (/design-patterns-template-method/)</strong>, in which it delegates the responsibility of variants in an algorithm to concrete classes. In the case of the <strong>Factory-Method</strong> pattern, the responsibility of creating objects is being delegated to the classes that implement the interface.</p>
</li>
<li>
<p>The <code>factoryMethod</code> <strong>method does not have to create new instances every time</strong>, but can return these objects from a memory cache, local storage, etc. What is important is that this method must return an object that implements the <code>Product</code> interface.</p>
</li>
</ol>
<h1 id="factorymethodpatternwhentouse">Factory-Method Pattern: When To Use</h1>
<ol>
<li>
<p>The problem solved by the pattern <strong>Factory-Method</strong> is easy to identify: <strong>The object with which the client must work is not known a priori</strong>, but this knowledge depends directly on the interaction of another user with the system (end-user or system). The traditional example where the need for this pattern arises is when the user selects an object type from a list of options.</p>
</li>
<li>
<p>In the event that <strong>it is necessary to extend the internal components</strong> (the number of objects that are created) without the need to have the code attached, but instead there is an interface that must be implemented and it should only be extended by creating a class relative to the new object to be included and its specific creator.</p>
</li>
</ol>
<h1 id="factorymethodpatternadvantagesanddisadvantages">Factory-Method Pattern: Advantages and Disadvantages</h1>
<p>The <em>Factory-Method</em> pattern has a number of advantages that can be summarized in the following points:</p>
<ul>
<li>
<p>The code is more maintainable because it is less coupled between the client classes and their dependencies.</p>
</li>
<li>
<p><strong>Clean code</strong> since the <em>Open-Closed Principle</em> is guaranteed due to new concrete classes of <code>Product</code> can be introduced without having to break the existing code.</p>
</li>
<li>
<p><strong>Cleaner code</strong> since the <em>Single Responsibility Principle (SRP)</em> is respected because the responsibility of creating the concrete <code>Product</code> is transferred to the concrete creator class instead of the client class having this responsibility.</p>
</li>
</ul>
<p>However, the main drawback of the <em>factory-method</em> pattern is the increased complexity in the code and the increased number of classes required. This a well-known disadvantage when applying design patterns — the price that must be paid to gain abstraction in the code.</p>
<hr>
<h1 id="factorymethodpatternexamples">Factory-Method pattern examples</h1>
<p>Next we are going to illustrate two examples of application of the <em>Factory-Method</em> pattern:</p>
<ol>
<li>
<p>Basic structure of the <strong>Factory-Method pattern</strong>. In this example, we'll translate the theoretical UML diagram into TypeScript code in order to identify each of the classes involved in the pattern.</p>
</li>
<li>
<p>A Point of Service (POS) of a fast food restaurant in which the <em>Factory-Method pattern</em> will be incorrectly applied resulting in a software pattern (not by design) known as <em>Simple-Factory</em> in which the <em>Open-Closed Principle</em> is not respected. However, this programming technique is really useful when no more abstraction is required than necessary. Although, the price to pay is high when you want to scale the project.</p>
</li>
<li>
<p>Resolution of the previous problem applying the <em>Factory-Method pattern</em>.</p>
</li>
</ol>
<p>The following examples will show the implementation of this pattern using TypeScript. We have chosen TypeScript to carry out this implementation rather than JavaScript — the latter lacks interfaces or abstract classes so the responsibility of implementing both the interface and the abstract class would fall on the developer.</p>
<hr>
<h1 id="example1basicstructureofthefactorymethodpattern">Example 1: Basic Structure of the Factory-Method Pattern</h1>
<p>In this first example, we’re going to translate the theoretical UML diagram into TypeScript to test the potential of this pattern. This is the diagram to be implemented:</p>
<p><img src="https://cdn-images-1.medium.com/max/2376/1*UmbP1kG7sTmBs5PsTC2jCw.jpeg" alt="Understanding Design Patters: Factory Method"></p>
<p>First of all, we are going to define the interface (<code>Product</code>) of our problem. As it is an interface, all the methods that must be implemented in all the specific products (<code>ConcreteProduct1</code> and <code>ConcreteProduct2</code>) are defined. Therefore, the <code>Product</code> interface in our problem is quite simple, as shown below:</p>
<pre><code class="language-javascript">export interface Product {
  operation(): string;
}
</code></pre>
<p>The objects that we want to build in our problem must implement the previously defined interface. Therefore, concrete classes <code>ConcreteProduct1</code> and <code>ConcreteProduct2</code> are created which satisfy the <code>Product</code> interface and implement the <code>operation</code> method.</p>
<pre><code class="language-javascript">import { Product } from &quot;./product.interface&quot;;

export class ConcreteProduct1 implements Product {
  public operation(): string {
    return &quot;ConcreteProduct1: Operation&quot;;
  }
}
</code></pre>
<pre><code class="language-javascript">import { Product } from &quot;./product.interface&quot;;

export class ConcreteProduct2 implements Product {
  public operation(): string {
    return &quot;ConcreteProduct2: Operation&quot;;
  }
}
</code></pre>
<p>The next step is to define the <code>Creator</code> abstract class in which an abstract <code>factoryMethod</code> must be defined, which is the one that will be delegated to the concrete classes for the creation of an instance of a concrete object. The really important thing is that it must return an object of the <code>Product</code> class.</p>
<p>On the other hand, the operation method has been defined which makes use of the <code>factoryMethod</code> abstract method. The <code>factoryMethod</code> method that is executed will be that of the concrete class in which it is defined.</p>
<pre><code class="language-javascript">import { Product } from &quot;./product.interface&quot;;

export abstract class Creator {
  protected abstract factoryMethod(): Product;

  public operation(): string {
    const product = this.factoryMethod();
    return `Creator: ${product.operation()}`;
  }
}
</code></pre>
<p>The classes responsible for creating concrete objects are called <code>ConcreteCreator</code>. Each of the <code>ConcreteCreator</code> classes implement the <code>factoryMethod</code> method in which a new object of the <code>ConcreteProduct1</code> or <code>ConcreteProduct2</code> class is created depending on the <code>creator</code> class that has been used.</p>
<pre><code class="language-javascript">import { ConcreteProduct1 } from &quot;./concrete-product1&quot;;
import { Creator } from &quot;./creator&quot;;
import { Product } from &quot;./product.interface&quot;;

export class ConcreteCreator1 extends Creator {
  protected factoryMethod(): Product {
    return new ConcreteProduct1();
  }
}
</code></pre>
<pre><code class="language-javascript">import { ConcreteProduct2 } from &quot;./concrete-product2&quot;;
import { Creator } from &quot;./creator&quot;;
import { Product } from &quot;./product.interface&quot;;

export class ConcreteCreator2 extends Creator {
  protected factoryMethod(): Product {
    return new ConcreteProduct2();
  }
}
</code></pre>
<p>Finally, we would see how the class <code>Client</code> or <code>Context</code> can select which objects created without prior knowledge, and how this pattern keeps the <em>Open-Closed Principle</em> (OCP).</p>
<pre><code class="language-javascript">import { ConcreteCreator1 } from &quot;./concrete-creator1&quot;;
import { ConcreteCreator2 } from &quot;./concrete-creator2&quot;;
import { Creator } from &quot;./creator&quot;;

function client(creator: Creator) {
  console.log(`Client: I'm not aware of the creator's class`);
  console.log(creator.operation());
}

const concreteCreator1 = new ConcreteCreator1();
const concreteCreator2 = new ConcreteCreator2();

client(concreteCreator1);

console.log(&quot;----------&quot;);

client(concreteCreator2);
</code></pre>
<h1 id="example2posofarestaurantsimplefactory">Example 2 - POS of a Restaurant (Simple-Factory)</h1>
<p>In this example, a solution will be developed that does not satisfy the <em>Factory-Method pattern</em> but uses a <em>FactoryManager</em> class that is responsible for building any object. This solution breaks with the <em>Open-Closed Principle</em>, in addition to having <em>spaghetti code</em> in the creation of objects. The interesting thing is that this same example is refactored into the following example using the <em>factory-method pattern</em>.</p>
<p>The solution proposed here is not a design pattern, but it is a solution that is widely used in the industry. In fact, it has been called <em>Simple Factory</em> and has serious problems as the application scales.</p>
<p>The application to be built is a simple application that allows you to create different types of objects: <code>Pizza</code>, <code>Burger</code> or <code>Kebab</code>.</p>
<p>The creation of these objects is not known a priori and depends on user interaction. The <code>ProductManager</code> class is in charge of building an object of a certain class through the <code>createProduct</code> method.</p>
<p>Below is the UML diagram of this first proposal. A priori the two problems of this solution are already observed:</p>
<ol>
<li>
<p>High coupling of the <code>ProductManager</code> class with the system.</p>
</li>
<li>
<p><em>Spaghetti code</em> in the <code>createProduct</code> method of the <code>ProductManager</code> class which is built with a <code>switch-case</code> that breaks the <em>Open-Closed Principle</em> when you want to extend to other types of products.</p>
</li>
</ol>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*oTqlvo3bT4cisBlH1QZkYw.jpeg" alt="Understanding Design Patters: Factory Method"></p>
<p>As in other examples, we will gradually show the code for the implementation of this solution. The <em>Product</em> interface is exactly the same as the one used in the solution proposed by the <em>Factory-Method pattern</em>.</p>
<pre><code class="language-javascript">export interface Product {
  operation(): string;
}
</code></pre>
<p>The next step consists of the implementation of each of the specific objects that you want to create in this problem: <code>Burger</code>, <code>Kebab</code> and <code>Pizza</code>.</p>
<pre><code class="language-javascript">import { Product } from &quot;./product.interface&quot;;

export class Burger implements Product {
  public operation(): string {
    return &quot;Burger: Results&quot;;
  }
}
</code></pre>
<pre><code class="language-javascript">import { Product } from &quot;./product.interface&quot;;

export class Kebab implements Product {
    public operation(): string {
        return 'Kebab: Operation';
    }
}
</code></pre>
<pre><code class="language-javascript">import { Product } from &quot;./product.interface&quot;;

export class Pizza implements Product {
    public operation(): string {
        return 'Pizza: Operation';
    }
}
</code></pre>
<p>Finally, we implement the <code>ProductManager</code> class, which is responsible for creating each of the object types based on the type parameter. An enum type has been used that allows us to avoid using strings in the use of the <code>switch-case</code> statement.</p>
<pre><code class="language-javascript">import { Burger } from &quot;./burger.model&quot;;
import { Kebab } from &quot;./kebab.model&quot;;
import { PRODUCT_TYPE } from &quot;./product-type.enum&quot;;
import { Pizza } from &quot;./pizza.model&quot;;

export class ProductManager {
  constructor() {}
  createProduct(type): Product {
    switch (type) {
      case PRODUCT_TYPE.PIZZA:
        return new Pizza();
      case PRODUCT_TYPE.KEBAB:
        return new Kebab();
      case PRODUCT_TYPE.BURGER:
        return new Burger();
      default:
        throw new Error(&quot;Error: Product invalid!&quot;);
    }
  }
}
</code></pre>
<p>Finally, it would be necessary to show the <code>Client</code> or <code>Context</code> class that makes use of the <code>productManager</code> class. Apparently from the <code>Client</code> class it is not observed that under this class there is a strongly coupled code that violates the principles of clean code.</p>
<pre><code class="language-javascript">import { PRODUCT_TYPE } from &quot;./product-type.enum&quot;;
import { ProductManager } from &quot;./product-manager&quot;;

const productManager = new ProductManager();

const burger = productManager.createProduct(PRODUCT_TYPE.BURGER);
const pizza = productManager.createProduct(PRODUCT_TYPE.PIZZA);
const kebab = productManager.createProduct(PRODUCT_TYPE.KEBAB);

console.log(burger.operation());
console.log(pizza.operation());
console.log(kebab.operation());
</code></pre>
<h1 id="example3posofarestaurantusingfactorymethod">Example 3 - POS of a Restaurant using Factory-Method</h1>
<p>In this example, we are going to take up the problem posed in Example 2 (POS of a restaurant) to propose the solution using the <em>factory-method pattern</em>. The objective of this solution is to avoid the <em>spaghetti code</em> that has been generated in the <code>productManager</code> class and to allow respecting the <em>Open-Closed Principle</em>.</p>
<p>Therefore, following the same methodology as the one we have presented in the previous examples, we are going to start by looking at the UML diagram that will help us identify each of the parts of this pattern.</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*AxszharDjB21rflYcUcPdQ.jpeg" alt="Understanding Design Patters: Factory Method"></p>
<p>In this case, the objects that we want to build would be those corresponding to the <code>Pizza</code>, <code>Burger</code> and <code>Kebab</code> classes. These classes implement the <code>Product</code> interface. All this part of code is identical to the one presented in the previous example. However, let's review the code to keep it in mind:</p>
<pre><code class="language-javascript">export interface Product {
   operation(): string;
}
</code></pre>
<pre><code class="language-javascript">import { Product } from &quot;./product.interface&quot;;

export class Burger implements Product {
  public operation(): string {
    return &quot;Burger: Results&quot;;
  }
}
</code></pre>
<pre><code class="language-javascript">import { Product } from &quot;./product.interface&quot;;

export class Kebab implements Product {
    public operation(): string {
        return 'Kebab: Operation';
    }
}
</code></pre>
<pre><code class="language-javascript">import { Product } from &quot;./product.interface&quot;;

export class Pizza implements Product {
    public operation(): string {
        return 'Pizza: Operation';
    }
}
</code></pre>
<p>On the other side of the UML diagram, we can find the <code>creator</code> classes. Let's start by reviewing the <code>Creator</code> class, which is responsible for defining the <code>factoryMethod</code> method, which must return an object that implements the <code>Product</code> interface. In addition, we will have the <code>someOperation</code> method which makes use of the <code>factoryMethod</code> abstract method which is developed in each of the concrete creator classes.</p>
<pre><code class="language-javascript">import { Product } from &quot;./product.interface&quot;;

export abstract class Creator {

    public abstract factoryMethod(): Product;

    public someOperation(): string {
        const product = this.factoryMethod();
        return `Creator: The same creator's code has just worked with ${product.operation()}`;
    }
}
</code></pre>
<p>We would still have to define each of the specific <code>BurgerCreator</code>, <code>KebabCreator</code> and <code>PizzaCreator</code> creator classes that will create each of the specific objects (NOTE: remember that it is not necessary to always create an object, if we had a structure of data from which instances that were cached were retrieved, the pattern would also be implemented).</p>
<pre><code class="language-javascript">import { Creator } from &quot;./creator&quot;;
import { Kebab } from &quot;./kebab.model&quot;;
import { Product } from &quot;./product.interface&quot;;

export class KebabCreator extends Creator {
    public factoryMethod(): Product {
        return new Kebab();
    }
}
</code></pre>
<pre><code class="language-javascript">import { Creator } from &quot;./creator&quot;;
import { Pizza } from &quot;./pizza.model&quot;;
import { Product } from &quot;./product.interface&quot;;

export class PizzaCreator extends Creator {
    public factoryMethod(): Product {
        return new Pizza();
    }
}
</code></pre>
<pre><code class="language-javascript">import { Burger } from &quot;./burger.model&quot;;
import { Creator } from &quot;./creator&quot;;
import { Product } from &quot;./product.interface&quot;;

export class BurgerCreator extends Creator {
  public factoryMethod(): Product {
    return new Burger();
  }
}
</code></pre>
<p>The last step we would have to complete our example would be to apply the pattern that we have developed using it from the <code>Client</code> or <code>Context</code> class. It is important to note that the <code>Client</code> function does not require any knowledge of the <code>Creator</code> or the type of object to be created. Allowing to fully delegate responsibility to specific classes.</p>
<pre><code class="language-javascript">import { BurgerCreator } from &quot;./burger-creator&quot;;
import { Creator } from &quot;./creator&quot;;
import { KebabCreator } from &quot;./kebab-creator&quot;;
import { PizzaCreator } from &quot;./pizza-creator&quot;;

function client(creator: Creator) {
    console.log('Client: I\'m not aware of the creator\'s class, but it still works.');
    console.log(creator.someOperation());
}

const pizzaCreator = new PizzaCreator();
const burgerCreator = new BurgerCreator();
const kebabCreator = new KebabCreator();


console.log('App: Launched with the PizzaCreator');
client(pizzaCreator);

console.log('----------');

console.log('App: Launched with the BurgerCreator');
client(burgerCreator);
</code></pre>
<p>Finally, I have created three <code>npm scripts</code> through which the code presented in this article can be executed:</p>
<pre><code class="language-javascript">npm run example1
npm run example2
npm run example3
</code></pre>
<p>GitHub Repo: <a href="https://github.com/Caballerog/blog/tree/master/factory-method-pattern">https://github.com/Caballerog/blog/tree/master/factory-method-pattern</a></p>
<h1 id="conclusion">Conclusion</h1>
<p><em>Factoy-Method</em> is a design pattern that allows respecting the <em>Open-Closed Principle</em> and delegates the responsibility for creating objects to specific classes using polymorphism. This allows us to have a much cleaner and more scalable code. It mainly solves the problem that arises when it is necessary to create different types of objects that depend on the interaction of a client with the system, and that it is not known a priori which object the client will create.</p>
<p>Finally, the most important thing about this pattern is not the specific implementation of it, but being able to recognize the problem that this pattern can solve, and when it can be applied. The specific implementation is the least of it since that will vary depending on the programming language used.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Understanding Design Patterns: Builder]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>There are 23 classic design patterns which are described in the original book <code>Design Patterns: Elements of Reusable Object-Oriented Software</code>. These patterns provide solutions to particular problems often repeated in software development.</p>
<p>In this article, I am going to describe how the <strong>Builder Pattern</strong> works and when it should be</p>]]></description><link>https://www.carloscaballero.io/understanding-design-patterns-builder/</link><guid isPermaLink="false">5fd7daad886c5e00010dfab5</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Carlos Caballero]]></dc:creator><pubDate>Thu, 17 Dec 2020 09:44:29 GMT</pubDate><media:content url="http://www.carloscaballero.io/content/images/2020/12/damir-spanic-1yPplLKKkqg-unsplash.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><img src="http://www.carloscaballero.io/content/images/2020/12/damir-spanic-1yPplLKKkqg-unsplash.jpg" alt="Understanding Design Patterns: Builder"><p>There are 23 classic design patterns which are described in the original book <code>Design Patterns: Elements of Reusable Object-Oriented Software</code>. These patterns provide solutions to particular problems often repeated in software development.</p>
<p>In this article, I am going to describe how the <strong>Builder Pattern</strong> works and when it should be applied.</p>
<h2 id="builderpatternbasicidea">Builder Pattern: Basic Idea</h2>
<blockquote>
<p>The <strong>builder pattern</strong> is a <a href="https://en.wikipedia.org/wiki/Software_design_pattern">design pattern</a> designed to provide a flexible solution to various object creation problems in <a href="https://en.wikipedia.org/wiki/Object-oriented_programming">object-oriented programming</a>. The intent of the Builder design pattern is to <a href="https://en.wikipedia.org/wiki/Separation_of_concerns">separate</a> the construction of a complex object from its representation — <a href="https://en.wikipedia.org/wiki/Builder_pattern">Wikipedia</a></p>
</blockquote>
<blockquote>
<p>Separate the construction of a complex object from its representation so that the same construction process can create different representations — Design Patterns: Elements of Reusable Object-Oriented Software</p>
</blockquote>
<p>On many occasions, the constructors of a class have a long list of arguments that have no semantic value, or that are not used by all instances of that class. This causes constructors to have a long list of arguments or having to define many constructors with different parameters, causing an explosion of constructor methods in the class.</p>
<p>The following code shows the classic problem in which there is a constructor with a list of parameters that must be initialized, even though the object in question does not require to have values in some of its attributes.</p>
<pre><code class="language-javascript">    new User('carlos', 'Caballero', 26, true, true, false, null, null);
</code></pre>
<p>The <strong>Builder pattern</strong> allows us to write clearer code, since it avoids the problem posed above. The UML diagram of this pattern is as follows:</p>
<p><img src="https://cdn-images-1.medium.com/max/3840/1*wDOZtAwnZqqp-a8VAc2qjA.png" alt="Understanding Design Patterns: Builder"></p>
<p>The classes that make up this pattern are the following:</p>
<ul>
<li>
<p><strong>Product</strong> is the concrete result of a construction process. That is, they will be the models of our application.</p>
</li>
<li>
<p><strong>Builder</strong> is a common interface for the concrete builders.</p>
</li>
<li>
<p><strong>ConcreteBuilder</strong> are different implementations of the constructive process. These classes will be responsible for clarifying the differences in the business logic of each of the object construction processes.</p>
</li>
</ul>
<p>These classes will be responsible for clarifying the differences between the business logic of each of the object construction processes.</p>
<ul>
<li>
<p><strong>Director</strong> defines the order in which the construction steps are performed. Its purpose is the reusability of specific configurations. The <code>Director</code> can be omitted in some implementations of this pattern, although its use is highly recommended, since it abstracts the client from the concrete steps of construction to the client.</p>
</li>
<li>
<p><strong>Client</strong> is the class that uses the pattern. There are two possibilities:</p>
</li>
</ul>
<p>1 - The client uses the <code>ConcreteBuilder</code>, executing the construction steps one by one.</p>
<p>2 - The client uses the <code>Director</code> which implements each of the construction processes, and acts as an intermediary between the <code>Client</code> and the <code>ConcreteBuilder</code> classes.</p>
<h2 id="builderpatternwhentouse">Builder Pattern: When To Use</h2>
<ol>
<li>
<p>The problem solved by the <strong>Builder pattern</strong> is easy to identify: this pattern should be used when it is necessary to use a constructor with a <strong>very long parameter list</strong> or <strong>when there is a long list of constructors with different parameters</strong>.</p>
</li>
<li>
<p>When it is necessary to build <strong>different representations of the same object</strong>. That is, when objects of the same class with different characteristics are needed.</p>
</li>
</ol>
<h2 id="builderpatternadvantagesanddisadvantages">Builder Pattern: Advantages and disadvantages</h2>
<p>The Builder pattern has a number of <em>advantages</em> that can be summarized in the following points:</p>
<ul>
<li>
<p>Objects can be created <strong>step by step.</strong></p>
</li>
<li>
<p>The creation of an object <strong>can be postponed</strong> until all the necessary information for the construction of the same is available. The object will not be obtained until the <code>build</code> method of the Builder class is executed.</p>
</li>
<li>
<p><strong>Clean code</strong>: The Single Responsibility Principle (SRP) is applied, since the complex construction of the object is isolated from the business logic of this object.</p>
</li>
</ul>
<p>However, the main drawback of the builder pattern is the increased complexity in the code, and the increased number of classes required. This a well known disadvantage when applying design patterns, since this is the price that must be paid in order to gain abstraction in the code.</p>
<p>Next we are going to illustrate three examples of application of the <strong>Builder pattern</strong>:</p>
<ol>
<li>
<p>Basic structure of the <strong>Builder pattern</strong>. In this example we are going to translate the theoretical UML diagram into TypeScript code in order to identify each of the classes involved in the pattern.</p>
</li>
<li>
<p>Creation of <strong>characters in a video game</strong>. Let’s think of the classic WoW (<em>World of Warcraft</em>) scenario in which the player can select between two races: Humans and Orcs.</p>
</li>
<li>
<p>Creation <strong>of products</strong> (Burgers) in a <strong>Point Of Sale</strong> (POS).</p>
</li>
</ol>
<p>The following examples will show the implementation of this pattern using TypeScript. We have chosen TypeScript to carry out this implementation rather than JavaScript, since the latter lacks interfaces or abstract classes and therefore, the responsibility of implementing both the interface and the abstract class would fall on the developer.</p>
<hr>
<h2 id="example1basicstructureofthebuilderpattern">Example 1 — Basic structure of the Builder pattern</h2>
<p>In this first example we are going to translate the theoretical UML diagram into TypeScript code to test the potential of this pattern. The diagram to be implemented is the following:</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*ypzQEbjEiU7jK6IuG990Zg.jpeg" alt="Understanding Design Patterns: Builder"></p>
<p>First we are going to define the model (<code>Product</code>) of our problem. In this class it is modeled that we will have a list of parts that is simply a list of strings . For this we define the classic <code>addPart</code>, <code>removePart</code> and <code>showParts</code> methods to manage this attribute.</p>
<p>However, note that the constructor of the object does not receive the list of initial parameters (in TypeScript it is not necessary to define it), but the model attribute will be modified through methods.</p>
<pre><code class="language-javascript">export class Product {
   public parts: string[] = [];

   public addPart(part: string): void {
       this.parts.push(part);
   }
   public removePart(part: string): void {
       this.parts = this.parts.filter(_part =&gt; _part !== part);
   }

   public showParts(): void {
       console.log(`Product parts: ${this.parts.join(', ')}\n`);
   }
}
</code></pre>
<p>The next step is to create the builder interface that defines the concrete builders. In the builder, the operations to add and remove each of the parts (A, B and C) are defined.</p>
<pre><code class="language-javascript">export interface Builder {
    addPartA(): void;
    addPartB(): void;
    addPartC(): void;
    removePartA(): void;
    removePartB(): void;
    removePartC(): void;
}
</code></pre>
<p>The concrete builder class has a private object of the class that we want to build (<code>Product</code>). The necessary modifications will be applied to its attributes to build the object according to each case.</p>
<p>Note that what the constructor method does is initialize the product, and that there is a <code>build</code> method that this is responsible of returning the object that has been configured in the <code>ConcreteBuilder1</code> class and reset the internal object to be able to build another object. The <code>ConcreteBuilder1</code> class configures a concrete object until the <code>build</code> method is invoked.</p>
<p>Note that what the constructor method does is initialize the product, and that there is a <code>build</code> method that is responsible of returning the object that has been configured in the <code>ConcreteBuilder1</code> class and resetting the internal object to be able to build another object. The <code>ConcreteBuilder1</code> class configures a concrete object until the <code>build</code> method is invoked.</p>
<pre><code class="language-javascript">import { Builder } from &quot;./builder.interface&quot;;
import { Product } from &quot;./product&quot;;

export class ConcreteBuilder1 implements Builder {
    private product: Product;

    constructor() {
        this.reset();
    }

    public reset(): void {
        this.product = new Product();
    }

    /**
     * Steps
     */
    public addPartA(): void {
        this.product.addPart('PartA1');
    }

    public addPartB(): void {
        this.product.addPart('PartB1');
    }

    public addPartC(): void {
        this.product.addPart('PartC1');
    }

    public removePartA(): void {
        this.product.removePart('PartA1');
    }

    public removePartB(): void {
        this.product.removePart('PartB1');
    }

    public removePartC(): void {
        this.product.removePart('PartC1');
    }

    public build(): Product {
        const result = this.product;
        this.reset();
        return result;
    }
}
</code></pre>
<p>Once we have the concrete operations to build an object through the <code>ConcreteBuild1</code> class, the next step is to define concrete steps to perform different constructions. The <code>Director</code> class is responsible for defining methods that specify the construction steps using the Builder object.</p>
<p>Therefore, the <code>Director</code> class receives an object from the Builder class as a parameter (in this case it would be BuilderConcrete1) and several constructions are defined:</p>
<ol>
<li>
<p><code>BasicObject</code> → It only consists of part A.</p>
</li>
<li>
<p><code>FullObject</code> → It consists of parts A, B and C.</p>
</li>
</ol>
<pre><code class="language-javascript">import { Builder } from &quot;./builder.interface&quot;;

export class Director {
    private builder: Builder;

    public setBuilder(builder: Builder): void {
        this.builder = builder;
    }

    public buildBasicObject(): void {
        this.builder.addPartA();
    }

    public buildFullObject(): void {
        this.builder.addPartA();
        this.builder.addPartB();
        this.builder.addPartC();
    }
}
</code></pre>
<p>Finally, it would be necessary to define the <code>Client</code> or <code>Context</code> class that makes use of the pattern. This client is quite clean since you only define the <code>Builder</code> object that you want to use and the creation of objects is invoked through the <code>Director</code>.</p>
<pre><code class="language-javascript">import { ConcreteBuilder1 } from './concrete-builder1';
import { Director } from './director';

function client(director: Director) {
    const builder = new ConcreteBuilder1();
    director.setBuilder(builder);

    console.log('A preconfigured basic object:');
    director.buildBasicObject();
    builder.build().showParts();

    console.log('A preconfigured full object:');
    director.buildFullObject();
    builder.build().showParts();

    // A custom object can be create without a Director class.
    console.log('Custom product:');
    builder.addPartA();
    builder.addPartC();
    builder.build().showParts();
}

const director = new Director();
client(director);
</code></pre>
<hr>
<h2 id="example2creationofheroesofavideogame">Example 2 —  Creation of Heroes of a video game</h2>
<p>Once the classic theoretical example has been presented to understand the responsibilities of each of the classes of the pattern, we are going to present another example in which we identify each of these classes with a specific problem.</p>
<p>Our problem is the representation of different heroes or characters in a video game. We will focus on the classic WoW (<em>World of Warcraft</em>) game, in which the heroes can be divided into two races: Humans and Orcs. In addition, each of these heroes can have <code>armor</code>, <code>weapon</code> or different <code>skills</code> depending on whether the hero is human or orc.</p>
<p>In the event that the <strong>Builder pattern</strong> is not applied, it causes a constructor to be defined in the Hero class with a long list of parameters (<code>race</code>, <code>armor</code>, <code>skills</code>...), which in turn, cause logic to be defined in the constructor to decide if the armor is human or orc. So, with this initial solution the problem is coupled since any change in the business logic would make rewriting quite a few pieces of code, with hardly any possibility of reuse.</p>
<p>In the event that the <strong>Builder pattern</strong> is not applied, it causes a constructor to be defined in the Hero class with a long list of parameters (<code>race</code>, <code>armor</code>, <code>skills</code>...), which in turn, causes logic to be defined in the constructor to decide whether the armor is human or orc. With this initial solution the problem is coupled, since any change in the business logic would require rewriting quite a few pieces of code, with hardly any possibility of reuse.</p>
<p>Therefore, the first thing we have to do is stop and think about how the <strong>Builder pattern</strong> helps us solve this problem. So, we focus on showing the UML diagram that solves this problem and we begin to implement it.</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*veQJQy779Jp8ulyOGVI0Lg.jpeg" alt="Understanding Design Patterns: Builder"></p>
<p>In this example we are going to follow the same order as in the previous example and we are going to start with the model or object that we want to build flexibly.</p>
<p>The Hero class defines the <code>race</code>, <code>armor</code>, <code>weapon</code> and <code>skills</code> properties which in our example for simplicity are simple character strings. All these attributes could be objects but to simplify the example we have left them as character strings.</p>
<pre><code class="language-javascript">export class Hero {
    public race: string;
    public armor: string;
    public weapon: string;
    public skills: string[];

    	
   public toString(): string {
        return `Hero:
                   race=${this.race ? this.race : 'empty'}
                   armor=${this.armor ? this.armor: 'empty'}
                   weapon=${this.weapon ? this.weapon: 'empty'}
                   skills=${this.skills ? this.skills: 'empty'}
                 `;
	}
}
</code></pre>
<p>The <code>HeroBuilder</code> interface defines the methods that the specific builders will have. Let’s observe that we will have the Hero object that will be configured little by little, each of the methods that allows the configuration of the object: <code>setArmor</code>, <code>setWeapon</code> and <code>setSkills</code>; and finally we will have the <code>build</code> method that finishes the configuration of the object and extracts the <code>Hero</code> object.</p>
<pre><code class="language-javascript">import { Hero } from &quot;./hero.model&quot;;

export abstract class HeroBuilder {
	protected hero: Hero;
	
	public abstract setArmor(): void;
  	public abstract setWeapon(): void;
  	public abstract setSkills(): void;

	public abstract build(): Hero;
}
</code></pre>
<p>Once the builder is defined (as an abstract class or interface) we must build the two specific builders that our problem requires: HumanHeroBuilder and OrcHeroBuilder. In the demo code we have completed with a different string according to each builder. It is important to note that the <code>build</code> method of each of the builders will return the built object (Hero) and reset the state of the object to be able to build another object.</p>
<pre><code class="language-javascript">import { Hero } from &quot;./hero.model&quot;;
import { HeroBuilder } from &quot;./hero-builder&quot;;

export class HumanHeroBuilder extends HeroBuilder {
   
    constructor() {
    	super();
        this.reset();
    }
	
    public reset() {
      	this.hero = new Hero();
        this.hero.race = &quot;Human&quot;;
    }
    
    public setArmor():void {
        this.hero.armor = &quot;Human armor&quot;;
    }
    
    public setWeapon(): void {
      	this.hero.weapon = 'Human weapon';
    }

    public setSkills(): void {
      	this.hero.skills = ['Human skill1', 'Human skill2'];
    }

    public build(): Hero {
      	const hero = this.hero;
      	this.reset();
      	return hero;
    }
}
</code></pre>
<pre><code class="language-javascript">import { Hero } from &quot;./hero.model&quot;;
import { HeroBuilder } from &quot;./hero-builder&quot;;

export class OrcHeroBuilder extends HeroBuilder {
   
    constructor() {
    	super();
        this.reset();
    }

    public reset() {
     	this.hero = new Hero();
        this.hero.race = &quot;Orc&quot;;
    }
    
    public setArmor():void {
        this.hero.armor = &quot;Orc armor&quot;;
    }
    
    public setWeapon(): void {
      	this.hero.weapon = 'Orc weapon';
    }

    public setSkills(): void {
      	this.hero.skills = ['Orc skill1', 'Orc skill2'];
    }

    public build(): Hero {
      	const hero = this.hero;
      	this.reset();
      	return hero;
    }
}
</code></pre>
<p>The last element of the pattern would be the <code>Hero-Director</code> class that allows you to store configurations that are repeated throughout the code. In our example we have created three <code>Hero</code> creation setups. For example, the <code>createHero</code> method builds a complete hero, that is, it assigns armor, abilities and weapons. In addition, we create a hero without any equipment through the <code>createHeroBasic</code> method and, finally, to illustrate another configuration, the <code>createHeroWithArmor</code> method is defined, which returns a hero in which only the armor has been assigned.</p>
<pre><code class="language-javascript">import { HeroBuilder } from &quot;./hero-builder&quot;;

export class HeroDirector {

    public createHero (heroBuilder: HeroBuilder) {
        heroBuilder.setArmor();
        heroBuilder.setSkills();
    	heroBuilder.setWeapon();
    	return heroBuilder.build();
  }
 
  public createHeroBasic (heroBuilder: HeroBuilder){
	return heroBuilder.build();
  }
    
  public createHeroWithArmor(heroBuilder: HeroBuilder){
	heroBuilder.setArmor();
    return heroBuilder.build();
 }

}
</code></pre>
<p>Finally, we will show a console client that makes use of the two builders that we have built throughout this example. In this example we create the two builders: <code>HumanHeroBuilder</code> and <code>OrcHeroBuilder</code>; and the director’s class: <code>HeroDirector</code>. As a demonstration, we will use the two builders together with the director to create the three hero configurations that the <code>HeroDirector</code> class has preconfigured.</p>
<pre><code class="language-javascript">import { HeroDirector } from &quot;./hero-director&quot;;
import { HumanHeroBuilder } from &quot;./human-hero-builder&quot;;
import { OrcHeroBuilder } from &quot;./orc-hero-builder&quot;;

const humanBuilder = new HumanHeroBuilder();
const orcBuilder = new OrcHeroBuilder();
const heroDirector = new HeroDirector();

const humanHero = heroDirector.createHero(humanBuilder);
const humanHeroWithArmor = heroDirector.createHeroWithArmor(humanBuilder);
const humanHeroBasic = heroDirector.createHeroBasic(humanBuilder);

console.log(humanHero.toString());
console.log(humanHeroWithArmor.toString());
console.log(humanHeroBasic.toString());

const orcHero = heroDirector.createHero(orcBuilder);
const orcHeroWithArmor = heroDirector.createHeroWithArmor(orcBuilder);
const orcHeroBasic = heroDirector.createHeroBasic(orcBuilder);

console.log(orcHero.toString());
console.log(orcHeroWithArmor.toString());
console.log(orcHeroBasic.toString());
</code></pre>
<hr>
<h2 id="example3creationofburgerspointofsale">Example 3 —  Creation of burgers (Point of Sale)</h2>
<p>In the following example we are going to create a POS for a burger restaurant. The main change in this example compared to the previous ones is that each modification operation of the object to be created, instead of not returning any value, will return the builder itself. In this way, the different operations to be carried out by the builder itself can be chained, since each operation returns the <code>Builder</code> object.</p>
<p>Following the same methodology that we have presented in the previous examples, we are going to start by looking at the UML diagram that will help us identify each of the parts of this pattern.</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*gJwzL4XkgppN_7E9gbPn4w.jpeg" alt="Understanding Design Patterns: Builder"></p>
<p>In this case, the object we want to build would be the one corresponding to the <code>Burger</code> class where there is a list of ingredients to configure in each of the burgers. The <code>Burger</code> class will have accessor methods corresponding to each of its attributes.</p>
<p>The code associated with this class is the following:</p>
<pre><code class="language-javascript">import { BurgerType } from &quot;./burger-type.interface&quot;;

export class Burger {
    public type: BurgerType = BurgerType.NORMAL;
    public cheese = false;
    public lettuce = false;
    public tomato = false;
    public double = false;
    public onion = false;
    public pickle = false;
    public bacon = false;
    public chiliSauce = false;
    public egg = false;

    public setType(type: BurgerType){
        this.type = type;
    }

    public setCheese() {
        this.cheese = true;
    }

    public setLettuce() {
        this.lettuce = true;
    }

    public setTomate() {
        this.tomato = true;
    }

    public setDouble() {
        this.double = true;
    }

    public setOnion() {
        this.onion = true;
    }

    public setPickle() {
        this.pickle = true;
    }

    public setBacon() {
       this. bacon = true;
    }

    public setChiliSauce() {
        this.chiliSauce = true;
    }

    public setEgg() {
        this.egg = true;
    }
}
</code></pre>
<p>In this example, the <code>BurgerType</code> enumerated type has been included, which allows defining the different types of burgers that exist in the application.</p>
<pre><code class="language-javascript">export enum BurgerType {
    NORMAL,
    CHEESE,
    VEGGIE,
    DOUBLE,
    CHEESE_BACON,
    DOTTECH,
    GODZILLA
}
</code></pre>
<p>In the <code>BurgerBuilder</code> class, each method performs the modification on the object that is being configured, and also, the builder is being returned to be able to chain the different operations. Of course, the <code>build</code> method still returns the <code>Burger</code> class object.</p>
<pre><code class="language-javascript">import { Burger } from &quot;./burger.model&quot;;
import { BurgerType } from &quot;./burger-type.interface&quot;;

export class BurgerBuilder {
    private burger: Burger;


    public constructor(){
        this.burger = new Burger();
    }

    public setType(type: BurgerType): BurgerBuilder{
        this.burger.setType(type);
        return this;
    }

    public setDouble(): BurgerBuilder{
        this.burger.setDouble();
        return this;
    }

    public addCheese(): BurgerBuilder{
        this.burger.setCheese();
        return this;
    }

    public addLettuce(): BurgerBuilder{
        this.burger.setLettuce();
        return this;
    }

    public addTomato(): BurgerBuilder{
        this.burger.setTomate();
        return this;
    }


    public addOnion(): BurgerBuilder{
        this.burger.setOnion();
        return this;
    }

    public addPickle(): BurgerBuilder{
        this.burger.setPickle();
        return this;
    }

    public addBacon(): BurgerBuilder{
        this.burger.setBacon();
        return this;
    }

    public addChiliSauce(): BurgerBuilder{
        this.burger.setChiliSauce();
        return this;
    }

    public addEgg(): BurgerBuilder{
        this.burger.setEgg();
        return this;
    }

    public build(): Burger{
        return this.burger;
    }
}
</code></pre>
<p>The <code>BurgerDirector</code> class is in charge of configuring the operations defined in the <code>BurgerBuilder</code> class. This is where you can see how different types of burgers are configured using the chained methods, which allows for ease of reading the code. It is important to remember that until the <code>build</code> method is executed, the same burger is being configured.</p>
<pre><code class="language-javascript">import { Burger } from &quot;./burger.model&quot;;
import { BurgerBuilder } from &quot;./burger-builder&quot;;
import { BurgerType } from &quot;./burger-type.interface&quot;;

export class BurgerDirector {

    public constructor(private builder: BurgerBuilder){
        this.builder = builder;
    }

    public serveRegularBurger(): Burger{
        return this.builder
                    .setType(BurgerType.NORMAL)
                    .build();
    }

    public serveCheeseBurger() : Burger{
        return this.builder
                    .addCheese()
                    .setType(BurgerType.CHEESE)
                    .build();
    }

    public serveVeggieBurger(): Burger{
        return this.builder
                    .addCheese()
                    .addLettuce()
                    .addTomato()
                    .setType(BurgerType.VEGGIE)
                    .build();
    }

    public serverDoubleBurger(): Burger{
        return this.builder.setDouble()
                      .setType(BurgerType.DOUBLE)
                      .build();
    }


    public serveCheeseBaconBurger(): Burger{
        return this.builder.addCheese()
                      .addBacon()
                      .setType(BurgerType.CHEESE_BACON)
                      .build();
    }
}
</code></pre>
<p>Finally, we show the client that uses the pattern. In this case, a random number is selected that defines a type of burger and the director is invoked to serve us that burger.</p>
<pre><code class="language-javascript">import { Burger } from &quot;./burger.model&quot;;
import { BurgerBuilder } from &quot;./burger-builder&quot;;
import { BurgerDirector } from &quot;./buger-director&quot;;

let burger: Burger;

const burgerType = Math.round(Math.random() * 6);
console.log('BurgerType: ', burgerType);

const burgerBuilder: BurgerBuilder = new BurgerBuilder();
const burgerDirector: BurgerDirector =  new BurgerDirector(burgerBuilder);


switch (burgerType) {
    case 1:
        burger = burgerDirector.serveRegularBurger();
        break;
    case 2:
        burger = burgerDirector.serveCheeseBurger();
        break;
    case 3:
        burger = burgerDirector.serveVeggieBurger();
        break;
    case 4:
        burger = burgerDirector.serverDoubleBurger();
        break;
    case 5:
        burger = burgerDirector.serveCheeseBaconBurger();
        break;
    case 6:
        burger = burgerDirector.serveDotTechBurger();
        break;
    default:
        burger = burgerDirector.serveGozillaBurger();
        break;
}

console.log(burger);
</code></pre>
<p>Finally, I have created three <code>npm</code> scripts through which the code presented in this article can be executed:</p>
<pre><code class="language-shell">    npm run example1
    npm run example2
    npm run example3
</code></pre>
<p>GitHub Repo: <a href="https://github.com/Caballerog/blog/tree/master/builder-pattern">https://github.com/Caballerog/blog/tree/master/builder-pattern</a></p>
<hr>
<h2 id="conclusion">Conclusion</h2>
<p>Builder is a design pattern that allows you to avoid having constructors with a long list of parameters in which not always all the parameters are required. It allows you to build instances of a certain object in a more flexible way, since you can configure only the attributes that are strictly necessary.</p>
<p>The code is much cleaner since there will be no parameters in the constructors that are not used, allowing only those parameters that are required to create the object to be used. Furthermore, since there is a <code>Director</code> class for the builders, the object creation configurations are reused so that there is no direct interaction with the Builder classes on the client.</p>
<p>Finally, the most important thing about this pattern is not the specific implementation of it, but being able to recognize the problem that this pattern can solve, and when it can be applied. The specific implementation is the least of it, since it will vary depending on the programming language used.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Why You Should Learn JavaScript?]]></title><description><![CDATA[<!--kg-card-begin: markdown--><h1 id="introduction">Introduction</h1>
<p>I am often asked which programming language is the ideal one to start learning to program. The answer to that question is very simple, the programming language does not matter but the important thing is logical reasoning and the first contact with a programming paradigm, the rest will go</p>]]></description><link>https://www.carloscaballero.io/why-you-should-learn-javascript/</link><guid isPermaLink="false">5f3bdc79886c5e00010df9e1</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Carlos Caballero]]></dc:creator><pubDate>Tue, 18 Aug 2020 16:02:31 GMT</pubDate><media:content url="http://www.carloscaballero.io/content/images/2020/08/markus-spiske-cSladFbk1bw-unsplash.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><h1 id="introduction">Introduction</h1>
<img src="http://www.carloscaballero.io/content/images/2020/08/markus-spiske-cSladFbk1bw-unsplash.jpg" alt="Why You Should Learn JavaScript?"><p>I am often asked which programming language is the ideal one to start learning to program. The answer to that question is very simple, the programming language does not matter but the important thing is logical reasoning and the first contact with a programming paradigm, the rest will go step by step as you immerse yourself in the industry.</p>
<p>However, the truth is that I have encountered many opponents in learning <em>JavaScript</em> because of its notoriety in the industry. It is true that JavaScript was born with a purpose and the industry has placed it by solving problems for which it was not originally intended. This has caused it to have such a bad reputation among veteran developers or those who come from other programming paradigms. But we cannot ignore that JavaScript is a living language, for more than five years (2015) it receives annual updates, it has a large community that is giving it support and reviewing possible improvements.</p>
<p>In this article, I am going to give you reasons <em>why you should learn JavaScript</em>. Apart from the fact that you do not want to dedicate yourself to the frontend, where it is its first execution environment.</p>
<hr>
<h1 id="1mostpopularprogramminglanguageintheworld">1. Most Popular Programming Language In The World</h1>
<p>This statement can harm lovers of exotic languages, who improve performance or security compared to other languages but are in the minority. In our case, JavaScript is the most used and popular programming language in the world, which makes it an excellent choice for a newbie.</p>
<p>This happens mainly because in the frontend world (on the Web) there is no other rival language. There is a monopoly of programming languages, in the past, it competed against VisualBasic Script, Action Script (Flash) or even with JAVA Applets. But none of these languages have survived JavaScript. In fact, the only language that nowadays begins to occupy a prominent position on the frontend is TypeScript, which is a JavaScript superset, and therefore, it is highly recommended to previously know how JavaScript works in depth.</p>
<p><img src="https://cdn-images-1.medium.com/max/2048/0*vF9SHLCBp1rb7rnQ.png" alt="Why You Should Learn JavaScript?"></p>
<hr>
<h1 id="2javascriptjobs">2. Javascript Jobs</h1>
<p>In any field or software development environment, we find several programming languages that solve the same type of problems. However, we have commented that JavaScript has a “monopoly” on the web application frontend market. That fact already places it in a privileged position compared to other languages. The most interesting thing to find jobs in JavaScript is that all the frontend tools/frameworks today are based on JavaScript, and it is highly recommended to know in depth how JavaScript works. That is, if we want to opt for a job in React, Vue and even Angular (it uses TypeScript as a language) you will need to have a knowledge of JavaScript.</p>
<p>Therefore, learning and understanding JavaScript will allow you to get a good and well-paid job. In fact, there is a big problem in the web development industry that will allow us to get a good job: <strong>There is a lack of professionals with solid knowledge in the JavaScript language.</strong></p>
<p><img src="https://cdn-images-1.medium.com/max/2968/0*0UWd2nhrJaP7Fgkp.png" alt="Why You Should Learn JavaScript?"></p>
<p>As of this writing (August, 2020) there are almost 40,000 jobs requiring JavaScript (in the US).</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*C2iv_p2aNm1imosj5kH2SQ.png" alt="Why You Should Learn JavaScript?"></p>
<p>Not only is it the number of jobs required, but the average salary: <strong>$117,717 per year.</strong></p>
<p><img src="https://cdn-images-1.medium.com/max/2146/1*eaRhO2Ap6dyaRQm105eVIA.png" alt="Why You Should Learn JavaScript?"></p>
<hr>
<h1 id="3itseverywhere">3. It’s Everywhere</h1>
<p>When I was a university student, I heard that Java was the revolution because we could write the code only once and it ran on all devices, and it is true that Java managed to abstract us from the operating system with its virtual machine. I felt in love with the idea behind JAVA, and today, we have a much easier and more comfortable “virtual machine” that are Web browsers (FireFox, Edge or Chrome) that execute JavaScript code. Therefore, in all the environments that a Web browser is installed, we will have JavaScript, this means that we can have practically all the devices that an end user can use.</p>
<p>This does not end here, for more than 10 years JavaScript can be executed on servers thanks to  <strong><a href="https://fossbytes.com/node-js-version-6-lts-released-features/">nodejs</a></strong>. In fact, this allows us to have code written in JavaScript on small devices without the need for a graphical environment.</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*uIJ6FkAD3NZOZsGbq-r06A.jpeg" alt="Why You Should Learn JavaScript?"></p>
<h1 id="4beginnerfriendly">4. Beginner-Friendly</h1>
<p>Again, I want to talk about my beginnings in Computer Science. When I began to develop software at the age of 11 (approximately) I first learnt the Pascal and C programming languages without tools, without the help of the compiler to know what was happening. In fact, it was quite hard to start learning to develop software and you needed a mentor to guide you a bit on this path.</p>
<p>Today, there are many facilities to start developing software, but JavaScript is a language that allows beginners to start developing software. Of course, this software will not be the best solution to the problem to be solved, but the novice will be writing lines of code and will have started his career in software development.</p>
<p>The next step <em>is to not stop learning</em>, to wonder how to improve and improve day by day, but you will already be in the world of development. That is, JavaScript is a novice friendly language, and this allows new developers to enter.</p>
<p>It is the task of the most veteran developers, to guide the newcomers on the right path of development; and for newbies to listen and learn from the experience of their fellow veterans. But that's another topic that we can discuss at another time.</p>
<p><img src="https://cdn-images-1.medium.com/max/7000/1*6nhEToVlrymDnpita2HnxQ.jpeg" alt="Why You Should Learn JavaScript?"></p>
<h2 id="5community">5. Community</h2>
<p>Being unique in the world is something that humans have sought for years. In fact, in the fashion, automotive or jewelry industry it is something that has an extra cost for users.</p>
<p>In our context, being unique or being alone is a danger. Our work is a collaborative one. It is a work in which you have to be totally synchronized with your colleagues and it is where being many is an advantage. That is, if the community of people who use the programming language, create libraries, solve doubts, help keep the language alive with revisions, these are advantages.</p>
<p>Now is when you discover that the size of the community is very important and that the JavaScript community is possibly the largest in the world compared to other languages (I do not have a statistical study of it, but it should be in the Top 3 with almost total certainty).</p>
<p>Some data that can help us deduce that the JavaScript community is one of the largest in the world are the following:</p>
<ul>
<li>
<p><strong>Largest StackOverflow Community.</strong> StackOverflow is the largest platform for programming Q&amp;A, and this is where you can see how the community helps solve problems of other colleagues.</p>
</li>
<li>
<p><strong>Largest Meetup Community.</strong> Meetup is a platform that allows you to connect people who have the same interest. In terms of programming languages, the number of communities dealing with JavaScript is the largest on the platform (approximately 3,600 and more than 1.5 Million members worldwide).</p>
</li>
<li>
<p><strong>Most-tagget language on GitHub.</strong> GitHub is the main opensource repository that exists today (acquired by Microsoft). In this platform, JavaScript is the most tagged programming language of all the projects that are hosted on this platform.</p>
</li>
</ul>
<p><img src="https://cdn-images-1.medium.com/max/6528/1*vCiLiH4Hv9nEl3kV-DorYA.jpeg" alt="Why You Should Learn JavaScript?"></p>
<h2 id="conclusions">Conclusions</h2>
<p>This post is not analyzing whether the JavaScript programming language is the best option to solve your problems. Whether it needs to transform or not, but we are looking at <strong>why you should learn JavaScript in 2020 and even for years to come</strong>.</p>
<p>It is an analysis looking at the positive points for you as a software developer and, of course, perhaps in a few years there will be another language or environment that will replace JavaScript but what you have learned in this language you can transfer to the next.</p>
<p>In my opinion, you should not miss the opportunity to learn JavaScript for its interesting advantages over other languages.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Automatic Adaptive Images in Angular Applications]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>In this posts series different tasks are described that can be automated to perform a deployment of frontend applications in Angular.</p>
<h1 id="postsseries">Posts Series</h1>
<ul>
<li><a href="https://www.carloscaballero.io/build-deploy-angular-apps-in-github-pages-using-github-actions/">Build &amp; Deploy Angular Apps en GitHub Pages con GitHub<br>
Actions</a></li>
<li><a href="https://www.carloscaballero.io/automatic-adaptive-images-in-angular/">Automatic Adaptive Images in Angular Applications</a></li>
</ul>
<hr>
<h1 id="introduction">Introduction</h1>
<p>Today, the users access to the Web apps through</p>]]></description><link>https://www.carloscaballero.io/automatic-adaptive-images-in-angular-applications/</link><guid isPermaLink="false">5edce153886c5e00010df765</guid><category><![CDATA[Angular]]></category><dc:creator><![CDATA[Carlos Caballero]]></dc:creator><pubDate>Mon, 08 Jun 2020 06:50:46 GMT</pubDate><media:content url="http://www.carloscaballero.io/content/images/2020/06/1_m196oUFF0LYLCGti8g_3bg.jpeg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><img src="http://www.carloscaballero.io/content/images/2020/06/1_m196oUFF0LYLCGti8g_3bg.jpeg" alt="Automatic Adaptive Images in Angular Applications"><p>In this posts series different tasks are described that can be automated to perform a deployment of frontend applications in Angular.</p>
<h1 id="postsseries">Posts Series</h1>
<ul>
<li><a href="https://www.carloscaballero.io/build-deploy-angular-apps-in-github-pages-using-github-actions/">Build &amp; Deploy Angular Apps en GitHub Pages con GitHub<br>
Actions</a></li>
<li><a href="https://www.carloscaballero.io/automatic-adaptive-images-in-angular/">Automatic Adaptive Images in Angular Applications</a></li>
</ul>
<hr>
<h1 id="introduction">Introduction</h1>
<p>Today, the users access to the Web apps through a wide variety of devices, such as laptops, tablets, smartPhones, desktop computers, etc..., which have different screen sizes and resolutions. On the other hand, one of the principles of accessibility is to get as many users as possible enriching and satisfying the experience in accessing applications overcoming both physical barriers (hearing, visual disabilities, cognitive, etc ...) as well as material or technological. Today, there are users who connect from different devices, as we have already indicated, and also with different technological features such as the bandwidth of internet network.</p>
<p>In addition, there are web applications that have high visual content, and therefore, a lot of images. These images are normally stored on a CDN (<em>Content-Delivery-Network</em>) from which the images are downloaded to the device.</p>
<p>In some specific areas of the world, or circumstances, downloading all these images can mean a bandwidth that is excessive for the users. Similarly, any optimization, even to users who have high performance devices is a benefit since the app will be available sooner.</p>
<p>In this post, we are going to show step by step how to build an Angular application with responsive images for different sizes although it could be for any technology.</p>
<h1 id="problemtosolve">Problem to solve</h1>
<p>The problem I have solved is the one I have experienced for the open source project <a href="https://www.angular-communities.com">Angular-Communities</a>. This project consists of a Google Map in which the shields of the different Angular communities around the world are displayed. Also, on a side-nav we find all the shields of the different communities, so we can navigate and select them for advanced information on those Angular communities. Allow me to tell you, just as an aside, do not hesitate and add your community to this map so that we can all have the information of your community.</p>
<p>In this specific problem, we had,at the date of this post, about 70 communities, each with its personalized shield. Each of these shields is an scalar image in PNG format that can be between <strong>13KiB – 186KiB</strong>. The 70 images have a size of <strong>2.6MiB</strong>. In this situation, we need to download all the images at the beginning, not being able to perform a technique <em>lazy</em> to download the images. This simplifies the code and the development complexity drastically. However, it seems worrying that all devices, no matter their sizes, have to download <strong>2.6MiB</strong> every time that access the website, causing an unnecessary loss of performance.</p>
<p>For this post, I have built a small demo in which all the images from <a href="https://www.angular-communities.com/">Angular-Communities</a> are downloaded in a single component with the final result of the post.</p>
<p>The following table shows the size of the images according to the format and the image size. It can be seen that the format getting the smallest file size, even with the same image size, is <code>.webp</code>.</p>
<script src="https://gist.github.com/Caballerog/79151a9568a08e2d8186f196f213243d.js"></script>
<hr>
<h1 id="createimagesofdifferentsizesandformats">Create images of different sizes and formats</h1>
<p>Imagine we had to edit each of the images with a software graphic editing, such as Gimp or Photoshop, manually. This would provoke a great amount of time invested just changing the size, quality and format of the images. We might think that doing this task only once for our task it could be a tedious but valid task (still I think that we should not do it manually, being able to do it automatically). However, this task gets more complicated if the images we want to carry out the process to gradually increases by interaction with the users or even if we have to make different adjustments to the sizes and qualities that we want to generate for each of the images.</p>
<p>Therefore, the ideal would be to have a tool/script that allows us to automate this task so that it is only a matter of executing a simple script and all our battery of images is generated automatically.</p>
<p>In our context, we are going to use a tool built using node.js since installing it and using it in our Angular application does not require the installation of new applications or package managers for different programming languages.</p>
<p>The chosen tool is <a href="https://github.com/MarcusCemes/responsive-image-builder">responsive-image-builder</a> (<em>RIB</em>), which is defined as a <em>building pipeline</em> of images in <code>WebP</code> format ultra fast for the Web. The time it will take to generate the images will depend on your processor or the processor of your integration system and the number of images to be transformed.</p>
<hr>
<h1 id="ribfeatures">RIB Features</h1>
<ul>
<li>⚡ Fast - Uses the lightning-quick [libvips</li>
<li>image processing](<a href="https://github.com/jcupitt/libvips/wiki/Speed-and-memory-use">https://github.com/jcupitt/libvips/wiki/Speed-and-memory-use</a>).</li>
<li>🔥 Multithreaded - Scales to all available CPU cores.</li>
<li>📦 Zero configuration - Change nothing, change everything. You choose.</li>
<li>🌍 Universal - a flexible image build process that doesn't enforce any principles.</li>
<li>✂️ Cross-platform - Tested on Windows, macOS and Linux.</li>
<li>😊 Friendly experience - telling you what's going on, from start to finish.</li>
<li>✨ SVG Tracing - for<a href="https://using-gatsby-image.gatsbyjs.org/traced-svg/"> really fancy placeholders</a>.</li>
</ul>
<p>All these features make this open-source tool ideal for our purpose. First of all, we install the package as a development dependency.</p>
<pre><code class="language-shellscript">npm i -D responsive-image-builder
</code></pre>
<p>The use of this tool is quite simple since we only have to specify the parameters of the following command:</p>
<pre><code class="language-shellscript">rib -i &lt;input&gt; -o &lt;output&gt; &lt;options&gt;
</code></pre>
<p>Therefore, if we want to include in our <em>deploy</em> pipeline that all the images in a certain directory are transformed and generated in a new directory, we can build the following <em>npm-script</em> that runs just before the <em>deploy</em> task.</p>
<pre><code class="language-shellscript">&quot;pre:deploy&quot;: &quot;rib -i src/assets/images_raw -o src/assets/images --no-clean --force&quot;
</code></pre>
<p>Although one of the characteristics of this tool/package is that it does not need configuration, in our specific case we want to build a <em>responsive</em> application in which each screen size has a set of images adjusted to its parameters. In other words, when a user accesses the Web page from a mobile device, they must download images that are the appropriate size for that device, images that are lighter than the ones for large screens, and when accessed from a device with a large screen, laptop or smartTV high resolution images can be enjoyed.</p>
<p>Therefore, we must configure the different sizes of images that we want to automatically generate. This configuration is done by creating a file called <code>.ribrc.json</code> in which an <em>array</em> is specified with the different configurations or image generation formats that you want to generate from each of the original images. Thus, each of the configurations allows you to specify a suffix using the <em>name</em> property, the width of the image using the <em>width</em> property, and that you want to force the creation of the image (it is overwritten if a previous one already exists) with the <em>force</em> property.</p>
<p>Therefore, in our configuration file, we are specifying that we will generate five images from each of the original images that will have the configurations as prefixes: <em>xs, sm, md, lg</em> and <em>xl</em>.</p>
<script src="https://gist.github.com/Caballerog/1c34cf46b25b9a4f244bd0b4c0cc205a.js"></script>
<p>Also, <code>rib</code> generates all images in the original format, <code>.png</code> or <code>.jpg</code> and in the <code>.webp</code> format. So if the browser supports the <code>.webp</code> format, it uses this one instead of the previous ones. The following section shows how you can delegate responsibility for using one image or another to the HTML (using the <code>picture</code> element).</p>
<p><img src="https://cdn-images-1.medium.com/max/1400/1*UTqGlThJj8EhCE5uW4fA1w.png" alt="Automatic Adaptive Images in Angular Applications"></p>
<hr>
<h1 id="elementopicture">Elemento Picture</h1>
<p>HTML5 introduced the <code>&lt;picture&gt;</code> element which allows more flexibility to specify images compared to the <code>&lt;img&gt;</code> element. The most common use of the <code>&lt;picture&gt;</code> element is to delegate responsibility for images in adaptive layouts to the browser via HTML. In other words, instead of scaling large images using the CSS <code>width</code> property, the most appropriate image can be selected depending on the device that is accessing the web application.</p>
<p>The <code>&lt;picture&gt;</code> element consists of two tags: one or more <code>&lt;source&gt;</code> elements and an <code>&lt;img&gt;</code> element. The browser checks the first <code>&lt;source&gt;</code> element that satisfies the <em>media query</em> with the device that is accessing the web application, and the image specified in the <code>srcset</code> attribute will be displayed. The <code>&lt;img&gt;</code> element is used as the <em>fallback</em> option in case the <em>media query</em> of any <code>&lt;source&gt;</code> element is not satisfied.</p>
<p>In our Angular component, we define an <em>array</em> of configuration of the images to show in the <em>template</em>. In this <em>array</em> we define several properties:</p>
<ul>
<li><em>min/max</em>: width <em>viewport</em> of the device that accesses the Web application.</li>
<li><em>suffix</em>: The image suffix.</li>
<li><em>format</em>: Format of the image, having the formats <code>.webp</code> and <code>.png</code>.</li>
</ul>
<script src="https://gist.github.com/Caballerog/9351f1a6e82140079f4ada58a60e321d.js"></script>
<p>In our <em>template</em>, we only need to go through the <em>array</em> defined above to generate the <code>&lt;source&gt;</code> and <code>&lt;img&gt;</code> elements to delegate responsibility to the <em>template</em>.</p>
<script src="https://gist.github.com/Caballerog/448244637eb43c57ea9155f556efb3d2.js"></script>
<hr>
<h1 id="result">Result</h1>
<p>The result obtained after performing these simple steps is that we have a directory with the images in <em>deploy</em> with different sizes and formats to be used depending on the device that accesses the Web application. The following images show the result of our application, which downloads some images or others depending on the device that accesses the application. The images show the images that would be downloaded by a mobile device and a large screen device (large monitors or television). In this way, we are providing greater accessibility to our Web application since <em>friendly</em> access to a greater number of devices is being allowed.</p>
<p><img src="https://cdn-images-1.medium.com/max/1400/1*V4CEcv9vpvilQSiof_f97w.png" alt="Automatic Adaptive Images in Angular Applications"></p>
<p><img src="https://cdn-images-1.medium.com/max/1400/1*YEWfEC34SI3jSU7GAA3b7g.png" alt="Automatic Adaptive Images in Angular Applications"></p>
<p>Finally, if you want to test the entire built system we only have to use the deployment <code>npm-script</code>, which can be integrated in a task of our CI/CD system as it is in the original project <a href="https://www.angular-communities.com">Angular- Communities</a> delegating the responsibility to carry out all this task to an automatic system.</p>
<hr>
<h1 id="conclusion">Conclusion</h1>
<p>In this post, we have been able to see how the performance and accessibility of a web application can be improved in an automated way, adapting the images according to the device that accesses the Web. In this way, users do not have to download images that are not suitable for their devices, allowing greater accessibility to the Web.</p>
<p>If we want to continue improving the performance of our Web applications, it is very easy to add a <em>Service Worker</em> that caches our static content, so that the device does not have to make requests for all the images every time  it logs in. This feature is interesting if the images are not dynamic, that is, they will not undergo changes in each request of the end user.</p>
<p>In future posts related to this series of deployment of our frontend application, we will present how to integrate the tests automatically, allowing us to have a more complete workflow in our CI/CD system and adapted to our needs.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Build&Deploy Angular Apps in GitHub Pages using GitHub Actions]]></title><description><![CDATA[<!--kg-card-begin: markdown--><h1 id="introduction">Introduction</h1>
<p>In many times, an integration or deployment system is needed quickly and<br>
effectively for our <em>frontend</em> applications. At other times, considerable time has been invested in the task of manually deploying our applications.</p>
<p>Nowadays, with the increase of <em>commits</em> and developers working on a software project, it is absolutely</p>]]></description><link>https://www.carloscaballero.io/build-deploy-angular-apps-in-github-pages-using-github-actions/</link><guid isPermaLink="false">5ea86d7e886c5e00010df5a3</guid><category><![CDATA[Angular]]></category><dc:creator><![CDATA[Carlos Caballero]]></dc:creator><pubDate>Wed, 29 Apr 2020 06:07:21 GMT</pubDate><media:content url="http://www.carloscaballero.io/content/images/2020/04/david-leveque-GpNOhig3LSU-unsplash.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><h1 id="introduction">Introduction</h1>
<img src="http://www.carloscaballero.io/content/images/2020/04/david-leveque-GpNOhig3LSU-unsplash.jpg" alt="Build&Deploy Angular Apps in GitHub Pages using GitHub Actions"><p>In many times, an integration or deployment system is needed quickly and<br>
effectively for our <em>frontend</em> applications. At other times, considerable time has been invested in the task of manually deploying our applications.</p>
<p>Nowadays, with the increase of <em>commits</em> and developers working on a software project, it is absolutely necessary to carry out this deployment automatically.</p>
<p>This article will introduce how to have a <strong>Build&amp;Deploy</strong> system for<br>
Angular applications using <em>GitHub Actions</em> and <em>GitHub Pages</em>. A prerequisite to follow this article is to have our application in the <em>GitHub repositories</em>.</p>
<hr>
<h1 id="1configureghpages">1. Configure gh-pages</h1>
<p>The first thing we need to do is have a branch configured where the static files will be served (html, css, js, images …). By default, GitHub has a branch called <code>gh-pages</code> linked to its static server that provides us with a domain in the following format <code>https://&lt;username&gt;.github.io/&lt;repository&gt;</code>. Therefore, the first thing we do is create the <code>gh-page</code> branch as shown in the following image.</p>
<p><img src="https://cdn-images-1.medium.com/max/800/1*JAKrLA2b-4UdF3_K62ge3Q.png" alt="Build&Deploy Angular Apps in GitHub Pages using GitHub Actions"></p>
<p>We need to delete the files of our project since what will have to be in this repository are the files of our application after the build process. The steps to remove the files in the <code>gh-pages</code> branch are the following:</p>
<pre><code class="language-bash">&gt; git fetch origin gh-pages
&gt; git checkout gh-pages
Branch 'gh-pages' set up to track remote branch 'gh-pages' from 'origin'.Switched to a new branch 'gh-pages'
</code></pre>
<p>Once that we are located in the appropriate branch, we only delete all the<br>
files.</p>
<pre><code class="language-bash">&gt; git rm -rf .
&gt; git add .
&gt; git commit -m &quot;remove files&quot;
&gt; git push
</code></pre>
<p>After these steps, your repository should be empty and then we are ready for the next step.</p>
<hr>
<h1 id="2setupannpmscriptfordeploy">2. Setup an npm-script for deploy</h1>
<p>The second step is to configure an <em>npm script</em> that allows us to perform the <em>build</em> operation instead of running this task from the terminal although Angular apps have an <em>npm script</em> related to the build operation. In our case, we need a more specific <em>script</em> in which it is specified that the <em>build</em> task will be done in <em>production</em> mode (<em>--prod</em>) and that the base address of our project will not be the root but the name of the repository <code>--base-href=/&lt;repository&gt;/.</code></p>
<p>Therefore, we go back to the <code>master</code> branch and proceed to configure the<br>
<code>package.json</code> file by adding the following <em>npm script</em>:</p>
<pre><code class="language-bash">git checkout master
</code></pre>
<p>We edit the <code>package.json</code> file.</p>
<pre><code class="language-bash">“deploy”: “ng build --prod --base-href=/angular-ci-cd/”
</code></pre>
<hr>
<h1 id="3githubactions">3. GitHub Actions</h1>
<p>This is the most interesting step of this article since it is in which we are going to make use of the own tool of GitHub, <strong>GitHub Actions</strong>. To do so, go to the <em>Actions</em> tab in GitHub. You will see several templates to<br>
start then.</p>
<p><img src="https://cdn-images-1.medium.com/max/1200/1*jqrEgSnALXPJ7mfiw4E-rQ.png" alt="Build&Deploy Angular Apps in GitHub Pages using GitHub Actions"><br>
<span class="figcaption_hack">GitHub Actions</span></p>
<p>These files are configurations in the <code>.yml</code> format. These files will be<br>
automatically created in the <code>.github/workflows</code> directory. In our specific case we will create a file called <code>build-deploy.yml</code> that will have the following content:</p>
<pre><code class="language-yml">name: Build and Deploy

on:
  push:
    branches:
      - master
jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout
      uses: actions/checkout@v1
    - uses: actions/setup-node@v1 #this installs node and npm for us
      with:
        node-version: '10.x'
    - uses: actions/cache@v1 # this allows for re-using node_modules caching, making builds a bit faster.
      with:
        path: ~/.npm
        key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
        restore-keys: |
          ${{ runner.os }}-node-    
    - name: Build
      run: |
        npm install
        npm run-script deploy
    - name: Deploy
      uses: JamesIves/github-pages-deploy-action@releases/v3
      with:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        BRANCH: gh-pages
        FOLDER: dist/angular-ci-cd
</code></pre>
<p>Let's begin to understand this file and what is being done. If you have worked previously with the <code>.YML</code>/<code>.YAML</code> file, you will already know that you must be very strict with blank or tabulated spaces since if the file is missing perfectly aligned or if you combine blank and tabulated spaces you will find problems.</p>
<ul>
<li><strong>name</strong>: The name of the <em>action</em> to be able to identify it from other <em>actions</em> that we configure.</li>
<li><strong>on</strong>: When should the <em>action</em> be triggered? In our case,<br>
we only want the <em>build</em> and <em>deploy</em> process to be done when a<br>
<em>push</em> operation on the <code>master</code> branch is done. Observe that for that purpose we have created different levels of indentation in the <code>build-deploy.yml</code> file. Although it is not the goal of this post, this trigger parameter allows us to build a CI system (<em>Continuous Integration</em>) in which the tests of our application could be executed for any <em>Pull Request</em>.</li>
<li><strong>jobs</strong>: This section defines the tasks that will be carried out<br>
in our <em>action</em>. Different tasks can be defined in one<br>
<em>action</em>. In our specific case we only need to configure a single<br>
task that we will call <em>build-and-deploy</em>. In this section is where you have to define each step in the task. Therefore, we define it in greater detail below.</li>
</ul>
<h2 id="jobs">Jobs</h2>
<p>The first element that is necessary to define a task is to assign a<br>
unique identifier or name, in this specific case it is build-and-deploy. The tasks can be executed in different environments, this is described using the <em>runs-on</em> section that, in our case, only one environment has been defined of execution since the task is to build and deploy our<br>
application. In the event that you want to configure test environments, this label is very interesting since it allows you to configure different environments in which will run the battery of tests on the application.</p>
<h2 id="steps">Steps</h2>
<p>The next item in our <code>.YML</code> file is the sequence of steps that<br>
performs the <em>action</em> that is being configured. The task we are configuring<br>
It is made up of three steps, which are as follows:</p>
<ol>
<li><em>Checkout.</em></li>
<li><em>Build.</em></li>
<li><em>Deploy.</em></li>
</ol>
<h3 id="1checkout">1. Checkout</h3>
<p>One of the most powerful features of <em>GitHub Actions</em> is that it allows<br>
use <em>actions</em> created by third parties. I mean, if you always<br>
we carry out the same steps we can parameterize and reuse them (that's a matter from another article different from this one). If we want to use a third party <em>action</em> we have to use the keyword <em>uses</em>, as shown in the<br>
code.</p>
<pre><code>- name: Checkout
  uses: actions/checkout@v1
</code></pre>
<p>In this task we are using the <em>actions/checkout@v1</em> which is<br>
find here: <a href="https://github.com/actions/checkout">https://github.com/actions/checkout</a></p>
<p><strong>What do we do in this task?</strong> Well, it is simple, this action performs the operation <em>check-out</em> from our repository on the GitHub workspace. I mean, we are performing the command <em>git checkout</em> in the <em>workspace</em> of our <em>GitHub Actions</em>. Thus, we have full access to the following steps of<br>
our flow.</p>
<h3 id="2build">2. Build</h3>
<p>The next step is to build our Angular application, exactly the same as we would do if we did it manually. So, we should install the dependencies using <code>npm install</code> and after should run the <code>npm-script</code> that we have configured for the building our application: <code>npm run-script build</code>. Therefore, the step called <code>Build</code> would be composed of these two steps, which we can describe using the <code>run</code> tag of <em>GitHub Actions</em>.</p>
<pre><code>- name: Build 
  run: | 
        npm install 
        npm run-script build
</code></pre>
<h3 id="3deploy">3. Deploy</h3>
<p>The last step is to perform the <em>deploy</em> of the application. The <em>deploy</em> of our application is quite simple because we only have static files (html, css and .js) once we have completed the <em>build</em> phase of An Angular application. Therefore, all we have to do is copy to adapt our application to <em>GitHub Pages</em>. This task is always the same mode, perhaps changing some settings. Therefore we will use of a third-party <em>action</em> that considerably facilitates the task: <a href="https://github.com/JamesIves/github-pages-deploy-action">https://github.com/JamesIves/github-pages-deploy-action</a></p>
<p>In this <em>action</em>, it is important that we have to configure a <em>TOKEN</em> of<br>
security to access the repository. There are different ways to display<br>
our applications using the <em>GitHub API</em>:</p>
<ol>
<li><strong>SSH</strong>: using a deploy key (<em>Deploy Key</em>).</li>
<li><strong>ACCESS_TOKEN</strong>: generating a secret key for a personal account<br>
GitHub, this must be done by creating a <em>secret</em> from the configuration panel from GitHub.</li>
<li><strong>GITHUB_TOKEN</strong>: GitHub automatically creates a secret<br>
called <code>GITHUB_TOKEN</code> to use in the <em>workflow</em>.</li>
</ol>
<p>We will use <code>GITHUB_TOKEN</code> for our deployment since it will be done from the GitHub itself to <em>GitHub Pages</em> therefore, we delegate the responsibility for security to the GitHub itself.</p>
<p>The following parameters that must be configured to deploy successfully in <em>GitHub Pages</em> are the branch (<em>BRANCH</em>) where you want deploy the code (<em>gh-pages</em>) and the directory (<em>FOLDER</em>) where the code is located.</p>
<p>The action to deploy (<em>Deploy</em>) is as shown below:</p>
<pre><code>- name: Deploy 
  uses: JamesIves/github-pages-deploy-action@releases/v3                             
  with:  
      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      BRANCH: gh-pages  
      FOLDER: dist/angular-ci-cd
</code></pre>
<h3 id="bonus">Bonus</h3>
<p>Using the previous steps it is enough to deploy our application. However, we may want to configure two extra steps that allow us to improve our <em>workflow</em>. An interesting configuration is that of require a specific version of <code>node</code> and/or have a cache of the <code>node</code> packages that have been previously installed so you don't have to install them on every <em>build</em>.</p>
<p>Therefore, the two steps that we need to configure are the following:</p>
<ol>
<li>setup-node.</li>
<li>cache.</li>
</ol>
<pre><code>- uses: actions/setup-node@v1 
  with:  
  node-version: '10.x'  
- uses: actions/cache@v1 
  with:     
    path: ~/.npm   
    key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}                   
    restore-keys: |    
       ${{ runner.os }}-node-
</code></pre>
<p>In the example above, the <code>node 10</code> version has been selected, and the<br>
cache files have followed the instructions of the <em>action</em> [<a href="https://github.com/actions/cache">https://github.com/actions/cache</a>] (<a href="https://github.com/actions/cache">https://github.com/actions/cache</a>) where<br>
according to the development language, it describes which files should be cached.</p>
<hr>
<h1 id="4verification">4. Verification</h1>
<p>Finally, we would have to check that the <em>Build&amp;Deploy</em> is being carried out, for this we move to the <em>GitHub Actions</em> tab where the <em>workflow</em> is shown.</p>
<p><img src="https://cdn-images-1.medium.com/max/1200/1*IpIK5wGt6vP6jPEDpDVnGA.png" alt="Build&Deploy Angular Apps in GitHub Pages using GitHub Actions"></p>
<p>If we navigate to the different panels we can see the <code>log</code> of each of<br>
tasks:</p>
<p><img src="https://cdn-images-1.medium.com/max/1200/1*4hclb4Gm8bdbuuZUfGC-wg.png" alt="Build&Deploy Angular Apps in GitHub Pages using GitHub Actions"></p>
<p>Here, you should see that all the steps have been done satisfactorily.</p>
<p><img src="https://cdn-images-1.medium.com/max/1200/1*vcjYVKNGj_JVsydIYNwXuA.png" alt="Build&Deploy Angular Apps in GitHub Pages using GitHub Actions"></p>
<p>Finally, we find our application in the URL: <code>https://&lt;user&gt;.github.io/&lt;repository&gt;</code>. In our case, We have the application deployed on this route:<br>
<a href="https://caballerog.github.io/angular-ci-cd/">https://caballerog.github.io/angular-ci-cd/</a></p>
<p><img src="https://cdn-images-1.medium.com/max/800/1*k54MXvHtyZAuBpzWOclHBA.png" alt="Build&Deploy Angular Apps in GitHub Pages using GitHub Actions"></p>
<hr>
<h1 id="conclusions">Conclusions</h1>
<p>In this post, we have presented a quick and easy way to have configured a <em>Build&amp;Deploy</em> system for Angular applications using <em>GitHub Actions</em> and <em>GitHub Pages</em>. The concepts learned in this article are transferable to any other continuous integration system.</p>
<p>Before using <em>GitHub Actions</em> and <em>GitHub Pages</em>, I've been deploying for months using <em>DroneCI</em> to a private static server and the concepts<br>
learned from that experience have been transferred to this system of<br>
continuous integration without any problem. Therefore, the concepts learned in this article can be easily transferred to other tools.</p>
<p>As of now, there is no excuse to deploy your applications in Angular from<br>
easy and fast way. Also, it works perfectly with private repositories.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item></channel></rss>