JavaScript Design Patterns - Chapter 1
Tags: javascript, webdev, programming, codequality
Published: 2021-01-20 20:34:18

# 🤓 INTRODUCTION

In this blog, I will discuss, and help you understand the design patterns using the JavaScript programming language. I will try to explain to you, what the pattern is, how do we use patterns, what is their structure, and much more. 

![office](https://media.giphy.com/media/1luXLMeNxsaNFMUuOe/giphy.gif)


No, no! Don't go all Michael Scott to me! Everything is fine, I'll try to stick to my word and keep it short, sweet, and simple. Because of that, I will deconstruct this into a series called 🎉 JavaScript Design Patterns Series. 🎉 (...a little generic but..🤷‍♂️)



# ▶ LET'S START  

One of the most important aspects of writing maintainable code is to be able to notice the recurring structures and functionalities in that code and optimize them. The knowledge that design patterns offer proves invaluable when it comes to writing maintainable code.

The design patterns father is  [Christopher Wolfgang Alexander](https://en.wikipedia.org/wiki/Christopher_Alexander), a widely influential British-American architect and design theorist, and currently emeritus professor at the University of California, Berkley.


# 🙄 WHAT IS PATTERN?

A pattern represents a reusable solution that can be applied to commonly occurring problems in software design. We could simplify and say that a pattern represents a template of **how to solve problems**


> 💡 Practical wisdom moment: Software Engineering is a problem-solving discipline!

### Why use Design Patterns?
- **Patterns are proven solutions**: They provide solid approaches to solving issues in software development using proven solutions that reflect the experience and insights the developers that helped define and improve them bring to the pattern.
- **Patterns can be easily reused**: A pattern usually reflects an out of the box solution that can be adapted to suit your own needs. This feature makes them quite robust.
- **Patterns can be expressive**: When you look at a pattern there's generally a set structure and so to say 'vocabulary' to the solution presented that can help express rather large solutions quite elegantly.

Patterns provide generalized solutions and can prevent that minor issues cause major problems in the application development process. Design patterns can often decrease file-size footprint while adding to a developer's vocabulary, which makes communication faster.

### Recurring phenomenon

One of the additional requirements for a pattern is to prove it's a recurring phenomenon. This is often something that can be qualified in at least three key areas, referred to as the rule of three.

- **Fitness of purpose** - how is the pattern considered successful
- **Usefulness** - why is the pattern considered successful
- **Applicability** - is the design worthy of being a pattern because it has wider applicability



 # 🏗 DESIGN PATTERN STRUCTURE

A pattern is presented in the form of a rule that establishes a relationship between:
- **A context**
- A system of **forces** that arises in that context
- A **configuration** that allows these forces to resolve themselves in context

### Design pattern ingredients
- **Pattern name**
- **Context outline** - the contexts in which the pattern is effective in responding to the user's needs
- **Problem statement** - a statement of the problem being addressed so we can understand the intent of the pattern
- **Solution** - a description of how the user's problem is being solved in an understandable list of steps and perceptions
- **Design**
- **Implementation** - a guide to how the pattern would be implemented
- **Illustration** - a visual representation of classes in the pattern
- **Examples** - implementation of the pattern in a minimal form
- **Co-requisites** - what other patterns may be needed to support the use of the pattern being described
- **Relations**
- **Known usage**
- **Discussions**



# 🏷 Categories of Design Pattern

### Creational Design Patterns

Creational design patterns focus on handling object creation mechanism where objects are created in a manner suitable for the situation you are working in. Some of the patterns that fall under this category are:
- **Constructor**
- **Factory**
- **Abstract**
- **Prototype**
- **Singleton**
- **Builder**

### Structural Design Patterns

Structural patterns are concerned with object composition and typically identify simple
ways to realize relationships between different objects. They help ensure that when one part of a system changes, the entire structure of the system doesn't need to do the same. Some of the patterns that fall under this category are:
- **Decorator**
- **Facade**
- **Flyweight**
- **Adapter**
- **Proxy**

### Behavioral Design Patterns

Behavioral patterns focus on improving or streamlining the communication between
disparate objects in a system. Some behavioral patterns include:
- **Iterator**
- **Mediator**
- **Observer**
- **Visitor**

# THE CONSTRUCTOR PATTERN

If you are already the JavaScript mage 🧙‍♂️, you are probably familiar with the constructor. Constructors are used for creating specific types of objects. The constructor prepares the object for use and accepts **parameters** which the constructor uses to set the values of **member variables** when the object is first created.

> 🛑 IMPORTANT:  [In JavaScript, there are no classes in the class-based OOP sense of the word. JavaScript works with objects. If you want to encapsulate a few functions and properties together, you would create an object containing functions and properties, and not a class.](https://medium.com/background-thread/why-javascript-is-an-oop-language-even-though-it-doesnt-have-classes-92a4e202176f#:~:text=In%20JavaScript%2C%20there%20are%20no,properties%2C%20and%20not%20a%20class.&text=JavaScript%20doesn't%20have%20blueprints%2C%20it%20only%20has%20houses.) 

In JavaScript, constructor functions are generally considered a reasonable way to implement instances. As we saw earlier, JavaScript doesn't support the concept of classes but it does support special constructor functions. By simply prefixing a call to a constructor function with the keyword "new", you can tell JavaScript you would function to behave like a constructor and instantiate a new object.

The simplest version of constructor pattern...

```javascript
function SuperHero(name, superPower, age, height, weight){
   this.that = this; //these are member variables
   this.name = name;
   this.superPower= superPower;
   this.age = age;
   this.height = height;
   this.weight = weight;
}

//A prototype function that prints out data about our 🦸‍♂️
SuperHero.prototype.getSuperHero= function(){
     return "Superhero stats: name="+this.name+", super power="+this.superPower
     +",age="+this.age+", height="+this.height+" feet, weight="+this.weight+" pounds";
}

//Instantiating objects with new keyword, and passing data to our SuperHero //constructor
var IronMan = new SuperHero('Tony Stark', 'Genious, Playboy, Philantropist', 30, 6, 225);
var Hulk = new SuperHero('Bruce Banner', 'Green scary monster', 30, 8, 1400);

console.log(IronMan.getSuperHero());
console.log(Hulk.getSuperHero());
``` 
Let's create an ES6 class that implements the same thing.

```javascript
//syntactic sugar on top of the prototype-based programming model
class SuperHero{
   constructor(name, superPower, age, height, weight){ //"classes constructor
     this.that = this; //these are member variables
     this.name = name;
     this.superPower= superPower;
     this.age = age;
     this.height = height;
     this.weight = weight;
   }
   
   //a "class" member function that prints out data about our 🦸‍♂️
   getSuperHero(){
      return "Superhero stats: name="+this.name+", super power="+this.superPower
     +",age="+this.age+", height="+this.height+" feet, weight="+this.weight+" pounds";
   }   
}

//Instantiating objects with new keyword, and passing data to the constructor of
//our superhero "class"
const IronMan =new SuperHero('Tony Stark', 'Genious, Playboy, Philantropist', 30, 6, 225);
const Hulk = new SuperHero('Bruce Banner', 'Green scary monster', 30, 8, 1400);

console.log(IronMan.getSuperHero());
console.log(Hulk.getSuperHero());
```

This is how we use and implement our constructor pattern.

In the next chapter, we will discuss a unique little fellow, the Singleton Pattern! :)

# 📝 SUMMARY

- **A pattern represents a reusable solution that can be applied to commonly occurring problems in software design.**
- **Patterns provide generalized solutions and can prevent that minor issues cause major problems in the application development process.**
- **In JavaScript, there are no classes in the class-based OOP sense of the word. JavaScript works with objects.**
- **Constructors are used for creating specific types of objects. The constructor prepares the object for use and accepts **parameters** which the constructor uses to set the values of **member variables** when the object is first created.**


# 🙏 THANK YOU FOR READING!
Please leave the comment, tell me about you, about your work, comment your thoughts, connect with me via  [Twitter](https://twitter.com/lazar_dev) or  [LinkedIn](https://www.linkedin.com/in/lazar-stankovic-44a199177/). 

Let this year be your year, let this year be our year. Until the next typing...

Have a nice time!

☕ SUPPORT ME AND KEEP ME FOCUSED!
<a href='https://ko-fi.com/Z8Z33D1HJ' target='_blank'><img height='36' style='border:0px;height:36px;' src='https://cdn.ko-fi.com/cdn/kofi4.png?v=2' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>
😊