Java Script Design Patterns – Let’s Explore

Java Script Design Patterns

Java Script Design Patterns

Overview: In this document we will talk about the different design patterns used in JavaScript. Most of the developers wonder to find out the exact or the ideal design pattern to be used in their program. To be honest, there is no concrete answer to this question or there aren’t any formulae which would find out the correct design pattern to be used in a given situation. So under such circumstance, we should have a firm gasp of the design patterns and the specific problems they deal with, we should be in a better situation to take a decision on which design pattern to be used in which condition.

Introduction:
A design pattern is a reusable solution which can be applied to common re-occurring problems in software design and development. Design pattern can also be termed as templates used to solve common problems. Design patterns have three major benefits:

  • They are proven solutions: Design pattern provide a solid approach in software development and uses proven techniques.
  • Can be easily reused: Design patterns are conceptual and provide out of the box solution which suits to our needs. This feature makes the design patterns more robust and they can be re-used in similar conditions.
  • Patterns are expressive: Every design pattern presents a predefined set structure and vocabulary which can be used to provide solutions to larger problems.

Design pattern never provides an exact solution to a problem. It is important to note that the role of patterns is to provide a solution scheme.

Types of Design Patterns
Design patterns can be divided into following three sub categories:

  • Creational Design Pattern : In this category the following design patterns fall :
    • Singleton
    • Constructor
    • Factory
    • Abstract
    • Prototype
    • Builder
  • Structural Design Pattern : In this category the following design patterns fall :
    • Decorator
    • Facade
    • Flyweight
    • Adapter
    • Proxy
  • Behavioral Design Pattern : In this category the following design pattern fall :
    • Iterator
    • Visitor
    • Mediator
    • Observer

Patterns in JavaScript:
The following patterns are commonly used in JavaScript:

  • Constructor Pattern
  • Module Pattern
  • Singleton Pattern
  • Observer Pattern
  • Mediator Pattern
  • Prototype Pattern
  • Command Pattern
  • Facade Pattern
  • Factory Pattern
  • Decorator Pattern
  • Flyweight Pattern

The Constructor Pattern:
As per the classical object oriented programming concept, a constructor is a special type of method which is used to create an instance of an object in the memory. In JavaScript object creation is done using any of the following three approaches:

Listing 1: Three approaches used in JavaScript to create Objects

[Code]

// Approach 1

var newObject = {};

//Approach 2

var newObject = Object.create(null);

//Approach 3

var newObject = new Object();

[/Code]

In the third approach, the Object is created using the Object constructor where no value is passed or set. There are multiple ways to set values to a newly created object. These are:

Listing 2: Ways to set values to a constructor

[Code]

//Approach 1

newObject.someKey = “Hello World”

//Approach 2

newObject[someKey] = “Hello World”

//Approach 3

Object.defineProperty( newObject, “someKey”, {

value : “Hello World”

writable : true

enumerable : true

configurable : true

);

[/Code]

The Singleton Pattern:
We all know that the singleton pattern restricts the creation of an object to single instance. Singleton pattern is implemented by creating a class with a method which creates a new instance of the object only when no other instances exist. In JavaScript singletons serve as a shared resource namespace which isolates implementation from the global namespace. In JavaScript, singleton is implemented in the following manner:

Listing 3: Singleton implementation in JavaScript

[Code]

var mySingleton = (function () {

// Instance stores a reference to the Singleton

var instance;

function init() {

// Singleton

// Private methods and variables

function privateMethod(){

console.log( “I am private” );

}

var privateVariable = “Im also private”;

var privateRandomNumber = Math.random();

return {

// Public methods and variables

publicMethod: function () {

console.log( “The public can see me!” );

},

publicProperty: “I am also public”,

getRandomNumber: function() {

return privateRandomNumber;

}

};

};

return {

// Get the Singleton instance if one exists

// or create one if it doesn’t

getInstance: function () {

if ( !instance ) {

instance = init();

}

return instance;

}

};

})();

var myBadSingleton = (function () {

// Instance stores a reference to the Singleton

var instance;

function init() {

// Singleton

var privateRandomNumber = Math.random();

return {

getRandomNumber: function() {

return privateRandomNumber;

}

};

};

return {

// Always create a new Singleton instance

getInstance: function () {

instance = init();

return instance;

}

};

})();

// Usage:

var single1 = mySingleton.getInstance();

var single2 = mySingleton.getInstance();

console.log( singleA.getRandomNumber() === singleB.getRandomNumber() ); // true

var badSingle1 = myBadSingleton.getInstance();

var badSingle2 = myBadSingleton.getInstance();

console.log( badSingleA.getRandomNumber() !== badSingleB.getRandomNumber() ); // true

[/Code]

As per the GoF, singleton is applicable in the following situations:

  • There should exist exactly on instance of the Object.
  • The sole instance should be extensible by sub-classing it.

The Observer Pattern:
In the Observer pattern, the object (also called as subject) maintains a list of objects depending on it referred to as observers. The subject automatically notifies to the observers any change that has happened, using the broadcast mechanism. Implementation of the Observer Pattern is shown below.

Listing 4: List of dependent Observers a subject may have

[Code]

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 ];  }}; ObserverList.prototype.Insert = function( obj, index ){  var pointer = -1;   if( index === 0 ){    this.observerList.unshift( obj );    pointer = index;  }else if( index === this.observerList.length ){    this.observerList.push( obj );    pointer = index;  }   return pointer;}; ObserverList.prototype.IndexOf = function( obj, startIndex ){  var i = startIndex, pointer = -1;   while( i < this.observerList.length ){    if( this.observerList[i] === obj ){      pointer = i;    }    i++;  }   return pointer;};  ObserverList.prototype.RemoveAt = function( index ){  if( index === 0 ){    this.observerList.shift();  }else if( index === this.observerList.length -1 ){    this.observerList.pop();  }};  // Extend an object with an extensionfunction extend( extension, obj ){  for ( var key in extension ){    obj[key] = extension[key];  }}

[/Code]

Listing 5: The Subject

[Code]

function Subject(){  this.observers = new ObserverList();} Subject.prototype.AddObserver = function( observer ){  this.observers.Add( observer );};   Subject.prototype.RemoveObserver = function( observer ){  this.observers.RemoveAt( this.observers.IndexOf( observer, 0 ) );};   Subject.prototype.Notify = function( context ){  var observerCount = this.observers.Count();  for(var i=0; i < observerCount; i++){    this.observers.Get(i).Update( context );  }};

[/Code]

In the above example, using the Observer components, we now define:

  • A button for adding new observable checkboxes to the page
  • A control checkbox which will act as a subject, notifying other checkboxes they should be checked
  • A container for the new checkboxes being added

The HTML code is as under

Listing 5: The HTML code

[Code]

<button id=”addNewObserver”>Add New Observer checkbox</button><input id=”mainCheckbox” type=”checkbox”/><div id=”observersContainer”></div>

[/Code]

Summary: So in this article I have discussed details about the JavaScript design patterns. The design patterns are applicable to all types of languages like object oriented language java and also scripting language like JavaScript. But there are differences and we have seen it in the examples above. So to conclude the discussion we can say that Design patterns are used to provide solution to commonly occurring problems. And please keep in mind that Design patterns are

  • Are Proven solution
  • Can be easily used
  • Are expressive

Hope you have understood the concepts and it will help you implement it in your own project. Happy reading.

More interesting articles on JS — You must read

Introduction to AngularJS

Foundation for Apps by Zurb

How to set CSS3 properties by Java Script?

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share