Daisy Rees

Daisy Rees

1569818959

10 JavaScript Design Patterns You Should Know

Every developer strives to write maintainable, readable, and reusable code. Code structuring becomes more important as applications become larger. Design patterns prove crucial to solving this challenge - providing an organization structure for common issues in a particular circumstance.

JavaScript web developers frequently interact with design patterns, even unknowingly, when creating applications.

Although there is a diverse list of design patterns used in certain circumstances, JavaScript developers tend to use some patterns customarily more than others.

In this post, I want to discuss these common patterns to expose ways to improve your programming repertoire and dive deeper into the JavaScript internals.

1. The constructor Pattern

In classical object-oriented programming languages, a constructor is a special method used to initialize a newly created object once the memory has been allocated for it. In JavaScript almost everything is an object, we have most often interested in object constructors. Since object constructors are used to creating specific types of objects, for example, both preparing the object for use and accepting arguments a constructor can use to set the values of member properties and methods when the object is first created.

10 JavaScript Design Patterns You Should Know

As we saw know JavaScript does not support the concept of classes, so inside a constructor, the keyword this references the new object that’s being created revisiting object creation, a basic constructor may look as follows:

function Car(model, year, miles) {
  this.model = model;
  this.year = year;
  this.miles = miles;
}

// Usage:
var bmw = new Car('M4', '2019', '1000');

2. The module Pattern

Modules are an integral piece of any robust application’s architecture and typically help in keeping the unit of code for a project cleanly separated and organized
There are several option for implementing modules. These include:

  • Object literal notation
  • The module Pattern
  • AMD modules
  • CommonJS module
  • ECMAScript Harmony modules

Object literals :

var newObject = {
  variableKey: variableValue,
  functionKey: function() {
    //…
  }
};

The modules Pattern:

10 JavaScript Design Patterns You Should Know

Let’s begin looking at an implementation of the Module pattern by created a module that is self-contained.

var testModule = (function() {
  var counter = 0;
  return {
    incrementCounter: function() {
      return ++counter;
    },
    resetCounter: function() {
      counter = 0;
    }
  };
})();

// Usage:
testModule.incrementCounter();
testModule.resetCounter();

3. The Revealing Module Pattern

One thing that the revealing module can do is avoiding repeat the name of the main object when we want to call one public method from another or access public variables.

var myRevealingModule = (function() {
  var privateVariable = 'not okay',
    publicVariable = 'okay';
  function privateFun() {
    return privateVariable;
  }

  function publicSetName(strName) {
    privateVariable = strName;
  }

  function publicGetName() {
    privateFun();
  }

  return {
    setName: publicSetName,
    message: publicVariable,
    getName: publicGetName
  };
})();

//Usage:

myRevealingModule.setName('Marvin King');

4. The Singleton Pattern

The Singleton pattern is thus known because it restricts instantiation of a class to single object. Singletons differ from static classes as we can delay their initialization. generally because they require some information that may not be available during initialization time. For code that is unaware of a previous reference to them, they do not provide a method for easy retrieval. Let’s have a look of the structure of singleton:

var singletonPattern = (function() {
  var instance;
  function init() {
    // Singleton
    function privateMethod() {
      console.log('privateMethod');
    }
    var privateVariable = 'this is private variable';
    var privateRandomNumber = Math.random();
    return {
      publicMethod: function() {
        console.log('publicMethod');
      },
      publicProperty: 'this is public property',
      getRandomNumber: function() {
        return privateRandomNumber;
      }
    };
  }

  return {
    // Get the singleton instance if one exists
    // or create if it doesn't
    getInstance: function() {
      if (!instance) {
        instance = init();
      }
      return instance;
    }
  };
})();

// Usage:
var single = singletonPattern.getInstance();

5. The Observer Pattern

The observer is a design pattern in which an object maintains a list of objects depending on it observers, automatically notifying them of any changes to state.

10 JavaScript Design Patterns You Should Know

  • Subject
    • Maintains a list of observers, facilities adding or removing observers
  • Observer
    • Provides an update interface for object that need to be notified of a subject’s change of state
  • ConcreteSubject
    • Broadcasts notifications to Observers on changes of state, stores the state of ConcreteObservers
  • ConcreteObserver
    • Stores a reference to the ConcreteSubject, implements an update interface for the observer to ensure state is consistent with subjects
function ObserverList() {
  this.observerList = [];
}

ObserverList.prototype.Add = function(obj) {
  return this.observerList.push(obj);
};

ObserverList.prototype.Empty = function() {
  this.observerList = [];
};

ObserverList.prototype.Count = function() {
  return this.observerList.length;
};

ObserverList.prototype.Get = function(index) {
  if (index > -1 && index < this.observerList.length) {
    return this.observerList[index];
  }
};

//...

When a subject needs to notify observers about something interesting happening, it broadcasts a notification to the observers ( including specific data related to the topic of the notification)

When we no longer wish for a particular observer the notified of changes by the subject it is registered with, the subject can remove it from the list of observers. In the future, I will talk more about the feature of how the observer can be used in JavaScript widely.

6. The Mediator Pattern

10 JavaScript Design Patterns You Should Know

If it appears a system has too many direct relationships between components. it may be time to have a central point of the control that components communicate through instead. The mediator pattern promotes loose coupling by ensuring that instead of components referring to each other explicitly.

var mediator = (function() {
  var topics = {};
  var subscribe = function(topic, fn) {
    if (!topics[topic]) {
      topics[topic] = [];
    }
    topics[topic].push({ context: this, callback: fn });
    return this;
  };

  // publish/broadcast an event to the rest of the application
  var publish = function(topic) {
    var args;
    if (!topics[topic]) {
      return false;
    }
    args = Array.prototype.slice.call(arguments, 1);
    for (var i = 0, l = topics[topic].length; i < l; i++) {
      var subscription = topics[topic][i];
      subscription.callback.apply(subscription.content, args);
    }
    return this;
  };
  return {
    publish: publish,
    subscribe: subscribe,
    installTo: function(obj) {
      obj.subscribe = subscribe;
      obj.publish = publish;
    }
  };
})();

7. The Prototype Pattern

One of the benefits of using the Prototype pattern is that we’ve working with the prototype strengths JavaScript has to offer natively rather than attempting to imitate features of other languages. let’s look at the pattern example.

var myCar = {
  name: 'bmw',
  drive: function() {
    console.log('I am driving!');
  },
  panic: function() {
    console.log('wait, how do you stop this thing?');
  }
};

//Usages:

var yourCar = Object.create(myCar);

console.log(yourCar.name); //'bmw'

8. The Factory Pattern

Factory can provide a generic interface for creating objects, where we can specify the type of factory object we wish to create. see the diagram below.

10 JavaScript Design Patterns You Should Know

function Car(options) {
  this.doors = options.doors || 4;
  this.state = options.state || 'brand new';
  this.color = options.color || 'silver';
}

9. The Mixin Pattern

Mixins are classes that offer functionality that can be easily inherited by a sub-class or group of sub-classes for the purpose of the function reuse.

var Person = function(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.gender = 'male';
};

var clark = new Person('Clark', 'kent');

var Superhero = function(firstName, lastName, powers) {
  Person.call(this.firstName, this.lastName);
  this.powers = powers;
};

SuperHero.prototype = Object.create(Person.prototype);
var superman = new Superhero('Clark', 'Kent', ['flight', 'heat-vision']);

console.log(superman); //output personal attributes as well as power

In this case, superhero is capable of overriding any inherited values with values specific to its object.

10 JavaScript Design Patterns You Should Know

10. The Decorator Pattern

The Decorators are a structural design pattern that aim to promote code reuse. Similar to Mixins, they can be considered another viable alternative to object subclassing. Classically, Decorators offered that ability to add behavior to existing classes in a system dynamically. The idea was the decoration itself wasn’t essential to the base functionality of the class. Let’s checkout how decorator work in JavaScript

function MacBook() {
  this.cost = function() {
    return 997;
  };
  this.screenSize = function() {
    return 11.6;
  };
}

// Decorator 1

function Memory(macbook) {
  var v = macbook.cost();
  macbook.cost = function() {
    return v + 75;
  };
}

// Decorator 2

function Engraving(macbook) {
  var v = macbook.cost();
  macbook.cost = function() {
    return v + 200;
  };
}

// Decorator 3

function Insurance(macbook) {
  var v = macbook.cost();
  macbook.cost = function() {
    return v + 250;
  };
}

var mb = new MacBook();

Memory(mb);
Engraving(mb);
Insurance(mb);

mb.cost(); // 1522

All the patterns may not use to one project, and some projects may benefit from the decoupling benefits offered by the Observer pattern. That said, once we have a firm grasp-of design patterns and the specific problems they are best suited to. Thus, it becomes much easier to integrate into our application architecture.

#javascript #design-pattern #web-development

What is GEEK

Buddha Community

10 JavaScript Design Patterns You Should Know
Samanta  Moore

Samanta Moore

1623835440

Builder Design Pattern

What is Builder Design Pattern ? Why we should care about it ?

Starting from **Creational Design Pattern, **so wikipedia says “creational design pattern are design pattern that deals with object creation mechanism, trying to create objects in manner that is suitable to the situation”.

The basic form of object creations could result in design problems and result in complex design problems, so to overcome this problem Creational Design Pattern somehow allows you to create the object.

Builder is one of the** Creational Design Pattern**.

When to consider the Builder Design Pattern ?

Builder is useful when you need to do lot of things to build an Object. Let’s imagine DOM (Document Object Model), so if we need to create the DOM, We could have to do lot of things, appending plenty of nodes and attaching attributes to them. We could also imagine about the huge XML Object creation where we will have to do lot of work to create the Object. A Factory is used basically when we could create the entire object in one shot.

As **Joshua Bloch (**He led the Design of the many library Java Collections Framework and many more) – “Builder Pattern is good choice when designing the class whose constructor or static factories would have more than handful of parameters

#java #builder #builder pattern #creational design pattern #design pattern #factory pattern #java design pattern

Madyson  Reilly

Madyson Reilly

1602747125

JavaScript — Build your object a builder!

Design Patterns

Before we will go over the builder design pattern, let’s briefly go over design patterns in general.

What is a Design Pattern?

A design pattern is a general and reusable solution for common problems you may encounter when designing your software. Each design pattern solves a different problem and can be customized to your use case with much ease.

Why do we need them?

One of the main reasons we need design patterns is to make our software very changeable, so it will be maintainable and will support future changes.

All software programs have to change and modify or they will cease to exist. The amount of time we spend on maintaining a software program is bigger than the amount of time it takes us to develop the program.

#javascript #javascript-tips #design-patterns #javascript-design-pattern #javascript-development

Giles  Goodwin

Giles Goodwin

1603184040

7 JavaScript Design Patterns Every Developer Should Know

A template for every project? Sounds amazing, isn’t it?

That’s also a level of coding I’m striving for.

One of the ways to achieve it is using design patterns, which help to write well-structured, beautiful, and organized codes.

In this story, we will discover some of the common design patterns used in JavaScript. Let’s get into it.

1. Constructor Pattern

You are familiar with constructors as functions that initialize objects with specific properties and methods.

The constructor pattern is similar to that definition. We use this pattern to create multiple instances of the same object.

There are many ways to create a new object in JavaScript. Take a look at the examples below:

// Using {} to create empty objects:
let person = {};

// Using Object() to create empty objects:
let person = new Object();
// Using function constructor:
function Person(name, age) {
  this.name = name;
  this.age = age;
  this.showName = () => console.log(this.name);
}
let person = new Person(‘Amy’, 28);
person.showName();

#javascript-development #design-patterns #javascript-tips #javascript #coding

Daisy Rees

Daisy Rees

1569818959

10 JavaScript Design Patterns You Should Know

Every developer strives to write maintainable, readable, and reusable code. Code structuring becomes more important as applications become larger. Design patterns prove crucial to solving this challenge - providing an organization structure for common issues in a particular circumstance.

JavaScript web developers frequently interact with design patterns, even unknowingly, when creating applications.

Although there is a diverse list of design patterns used in certain circumstances, JavaScript developers tend to use some patterns customarily more than others.

In this post, I want to discuss these common patterns to expose ways to improve your programming repertoire and dive deeper into the JavaScript internals.

1. The constructor Pattern

In classical object-oriented programming languages, a constructor is a special method used to initialize a newly created object once the memory has been allocated for it. In JavaScript almost everything is an object, we have most often interested in object constructors. Since object constructors are used to creating specific types of objects, for example, both preparing the object for use and accepting arguments a constructor can use to set the values of member properties and methods when the object is first created.

10 JavaScript Design Patterns You Should Know

As we saw know JavaScript does not support the concept of classes, so inside a constructor, the keyword this references the new object that’s being created revisiting object creation, a basic constructor may look as follows:

function Car(model, year, miles) {
  this.model = model;
  this.year = year;
  this.miles = miles;
}

// Usage:
var bmw = new Car('M4', '2019', '1000');

2. The module Pattern

Modules are an integral piece of any robust application’s architecture and typically help in keeping the unit of code for a project cleanly separated and organized
There are several option for implementing modules. These include:

  • Object literal notation
  • The module Pattern
  • AMD modules
  • CommonJS module
  • ECMAScript Harmony modules

Object literals :

var newObject = {
  variableKey: variableValue,
  functionKey: function() {
    //…
  }
};

The modules Pattern:

10 JavaScript Design Patterns You Should Know

Let’s begin looking at an implementation of the Module pattern by created a module that is self-contained.

var testModule = (function() {
  var counter = 0;
  return {
    incrementCounter: function() {
      return ++counter;
    },
    resetCounter: function() {
      counter = 0;
    }
  };
})();

// Usage:
testModule.incrementCounter();
testModule.resetCounter();

3. The Revealing Module Pattern

One thing that the revealing module can do is avoiding repeat the name of the main object when we want to call one public method from another or access public variables.

var myRevealingModule = (function() {
  var privateVariable = 'not okay',
    publicVariable = 'okay';
  function privateFun() {
    return privateVariable;
  }

  function publicSetName(strName) {
    privateVariable = strName;
  }

  function publicGetName() {
    privateFun();
  }

  return {
    setName: publicSetName,
    message: publicVariable,
    getName: publicGetName
  };
})();

//Usage:

myRevealingModule.setName('Marvin King');

4. The Singleton Pattern

The Singleton pattern is thus known because it restricts instantiation of a class to single object. Singletons differ from static classes as we can delay their initialization. generally because they require some information that may not be available during initialization time. For code that is unaware of a previous reference to them, they do not provide a method for easy retrieval. Let’s have a look of the structure of singleton:

var singletonPattern = (function() {
  var instance;
  function init() {
    // Singleton
    function privateMethod() {
      console.log('privateMethod');
    }
    var privateVariable = 'this is private variable';
    var privateRandomNumber = Math.random();
    return {
      publicMethod: function() {
        console.log('publicMethod');
      },
      publicProperty: 'this is public property',
      getRandomNumber: function() {
        return privateRandomNumber;
      }
    };
  }

  return {
    // Get the singleton instance if one exists
    // or create if it doesn't
    getInstance: function() {
      if (!instance) {
        instance = init();
      }
      return instance;
    }
  };
})();

// Usage:
var single = singletonPattern.getInstance();

5. The Observer Pattern

The observer is a design pattern in which an object maintains a list of objects depending on it observers, automatically notifying them of any changes to state.

10 JavaScript Design Patterns You Should Know

  • Subject
    • Maintains a list of observers, facilities adding or removing observers
  • Observer
    • Provides an update interface for object that need to be notified of a subject’s change of state
  • ConcreteSubject
    • Broadcasts notifications to Observers on changes of state, stores the state of ConcreteObservers
  • ConcreteObserver
    • Stores a reference to the ConcreteSubject, implements an update interface for the observer to ensure state is consistent with subjects
function ObserverList() {
  this.observerList = [];
}

ObserverList.prototype.Add = function(obj) {
  return this.observerList.push(obj);
};

ObserverList.prototype.Empty = function() {
  this.observerList = [];
};

ObserverList.prototype.Count = function() {
  return this.observerList.length;
};

ObserverList.prototype.Get = function(index) {
  if (index > -1 && index < this.observerList.length) {
    return this.observerList[index];
  }
};

//...

When a subject needs to notify observers about something interesting happening, it broadcasts a notification to the observers ( including specific data related to the topic of the notification)

When we no longer wish for a particular observer the notified of changes by the subject it is registered with, the subject can remove it from the list of observers. In the future, I will talk more about the feature of how the observer can be used in JavaScript widely.

6. The Mediator Pattern

10 JavaScript Design Patterns You Should Know

If it appears a system has too many direct relationships between components. it may be time to have a central point of the control that components communicate through instead. The mediator pattern promotes loose coupling by ensuring that instead of components referring to each other explicitly.

var mediator = (function() {
  var topics = {};
  var subscribe = function(topic, fn) {
    if (!topics[topic]) {
      topics[topic] = [];
    }
    topics[topic].push({ context: this, callback: fn });
    return this;
  };

  // publish/broadcast an event to the rest of the application
  var publish = function(topic) {
    var args;
    if (!topics[topic]) {
      return false;
    }
    args = Array.prototype.slice.call(arguments, 1);
    for (var i = 0, l = topics[topic].length; i < l; i++) {
      var subscription = topics[topic][i];
      subscription.callback.apply(subscription.content, args);
    }
    return this;
  };
  return {
    publish: publish,
    subscribe: subscribe,
    installTo: function(obj) {
      obj.subscribe = subscribe;
      obj.publish = publish;
    }
  };
})();

7. The Prototype Pattern

One of the benefits of using the Prototype pattern is that we’ve working with the prototype strengths JavaScript has to offer natively rather than attempting to imitate features of other languages. let’s look at the pattern example.

var myCar = {
  name: 'bmw',
  drive: function() {
    console.log('I am driving!');
  },
  panic: function() {
    console.log('wait, how do you stop this thing?');
  }
};

//Usages:

var yourCar = Object.create(myCar);

console.log(yourCar.name); //'bmw'

8. The Factory Pattern

Factory can provide a generic interface for creating objects, where we can specify the type of factory object we wish to create. see the diagram below.

10 JavaScript Design Patterns You Should Know

function Car(options) {
  this.doors = options.doors || 4;
  this.state = options.state || 'brand new';
  this.color = options.color || 'silver';
}

9. The Mixin Pattern

Mixins are classes that offer functionality that can be easily inherited by a sub-class or group of sub-classes for the purpose of the function reuse.

var Person = function(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.gender = 'male';
};

var clark = new Person('Clark', 'kent');

var Superhero = function(firstName, lastName, powers) {
  Person.call(this.firstName, this.lastName);
  this.powers = powers;
};

SuperHero.prototype = Object.create(Person.prototype);
var superman = new Superhero('Clark', 'Kent', ['flight', 'heat-vision']);

console.log(superman); //output personal attributes as well as power

In this case, superhero is capable of overriding any inherited values with values specific to its object.

10 JavaScript Design Patterns You Should Know

10. The Decorator Pattern

The Decorators are a structural design pattern that aim to promote code reuse. Similar to Mixins, they can be considered another viable alternative to object subclassing. Classically, Decorators offered that ability to add behavior to existing classes in a system dynamically. The idea was the decoration itself wasn’t essential to the base functionality of the class. Let’s checkout how decorator work in JavaScript

function MacBook() {
  this.cost = function() {
    return 997;
  };
  this.screenSize = function() {
    return 11.6;
  };
}

// Decorator 1

function Memory(macbook) {
  var v = macbook.cost();
  macbook.cost = function() {
    return v + 75;
  };
}

// Decorator 2

function Engraving(macbook) {
  var v = macbook.cost();
  macbook.cost = function() {
    return v + 200;
  };
}

// Decorator 3

function Insurance(macbook) {
  var v = macbook.cost();
  macbook.cost = function() {
    return v + 250;
  };
}

var mb = new MacBook();

Memory(mb);
Engraving(mb);
Insurance(mb);

mb.cost(); // 1522

All the patterns may not use to one project, and some projects may benefit from the decoupling benefits offered by the Observer pattern. That said, once we have a firm grasp-of design patterns and the specific problems they are best suited to. Thus, it becomes much easier to integrate into our application architecture.

#javascript #design-pattern #web-development

Jolie  Reichert

Jolie Reichert

1597554480

JavaScript Design Patterns

A pattern describes a Challange that happens over and another time in the environment, so describes the core of the answer thereto challenge, in such how that you simply will use this resolution a Tillion times over, without doing the same things twice.

In application development,it is important to focus on the strategy of constructing, associating application in a very healthy, very strong, and easily maintainable approach, patterns offer a way of giving names to solutions for common challenges. These solutions can vary from abstract to really precise and technical and allow developers to effectively communicate with each other.

The goal of this series is to whet your appetency for a somewhat formal discussion of knowledge in code development by introducing you to the thought of code vogue patterns and presenting a couple of patterns that ar fascinating as a result of they get used considerably in fashionable JavaScript comes.

Singleton pattern

The what

The singleton pattern isn’t one of the most widely used ones, but we’re starting here because it’s relatively easy to understand

The singleton pattern stems from the mathematical construct of a singleton that is:

In mathematics, a singleton, which is also known as a unit set, is a set with exactly one element. For example, the set {null} is a singleton.

The Singleton Pattern limits the number of instances of a particular object to just one. This single instance is called a singleton.

This simply means that we limit the actualization of a class to a single object. The primary time an object of a class implementing the singleton pattern should be incorporated, it is actually going to get incorporated. Any subsequent try is just going to return that first instance.

Image for post

#patterns #design-patterns #javascript