DEV Community

Cover image for JavaScript Design Patterns - Chapter 1
devlazar
devlazar

Posted on • Updated on

JavaScript Design Patterns - Chapter 1

πŸ€“ 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

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, 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.

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...

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());
Enter fullscreen mode Exit fullscreen mode

Let's create an ES6 class that implements the same thing.

//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());
Enter fullscreen mode Exit fullscreen mode

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 or LinkedIn.

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!
Buy Me a Coffee at ko-fi.com
😊

Top comments (2)

Collapse
 
powerwebdev profile image
powerwebdev

I'm not sure if you can call a "Constructor" a design pattern, it is more a language specific thing. So maybe it is an Idiom.

The first version using "function" and "new" is totally language specific, the second is more common in OO languages, but still a language feature.

But the problem it tries to solve is not limited to JavaScript, so calling the solution a JS design pattern is also not really suitable, because then it does not solve the problem its name implies.

But I'm curious, is there any reference to an actual PLoP conference publication that really qualifies it as a design pattern?

Collapse
 
devlazar profile image
devlazar

Thank you for your reply. I do agree that the constructor is a language-specific thing. These JS series are designed to tackle the concept of design patterns using a specific programming language, JavaScript, thus, JS Design Patterns. The same paradigm is transferable to many other languages, and could also be written in pseudo-language. Would you like me to include pseudo-code in the next chapter? 😊

There are no official PLoP conference references regarding constructor pattern that I could find, there are a couple of references in the books you can find on Amazon or in a nearby bookstore. But I would like to mention that it is a common practice in the University I went to, to represent constructor in such a manner because of the coding newbies, that are not familiar with how an instance of an object is being created. I really try to combine the Uni knowledge with official publications, primarily to get the coding newbies into the world of software engineering, but also, to be concise, simple, and effective. The next chapter is all about a unique little fellow, The Singleton Pattern! πŸš€