How to Use Javascript Singleton Design Pattern with an Example

by Luke P. Issac on June 10, 2014

Design pattern generally solves few typical programming challenges and makes it more scalable, reusable and meaningful.

It provides a generalized solution for frequently encountered problems, which typically tends to increase the total number of lines of code a program has to write.

The following are few benefits of understanding and using Design Patterns:

  • Modular code
  • Reusable code
  • Increased readability
  • More meaningful code from semantic perspective
  • Avoid time consuming problems implicitly
  • Reduce repetition of code
  • Highly scalable code
  • Supports object-oriented approach

Lets take Javascript and discuss design patterns in javascript to understand it better.

According to dimensions of code, on which a design pattern impacts, it can be categorized as follows:

  1. Creational Design Pattern
  2. Behavioral Design Pattern
  3. Structural Design Pattern

Lets take one type of pattern and see how design pattern solves the problem.

Creational Design Pattern

Creational design pattern basically deals with the way of creating objects in a way suitable to our requirements.

Different Creational design patterns can be used in different ways of creating objects as per our requirement. The basic ways of creating objects may not be suitable to all situations.

Lets discuss a good example of creational design pattern called “Singleton Pattern”

Singleton Pattern

This pattern ensure that, there is not, more than one instance of the class, ever created in the memory.

Whenever, you have to use same class with some initialization again and again we can make it as a singleton.

The object of this class should not be having the values being manipulated and changed over the time, because it is going be used several times at different fragment of time, in your code.

The script below implements Singleton Pattern:

var Person = (function(){

  // Self calling function
  // Private property for holding the only existing instance
  var personInstance;

  var createPerson = function(){
    // Private property initializing default pull capacity.
    var canPullWeight = 3;

    // Private method for increasing the value of canPullWeight.
    var canPull = function( kg ){
        canPullWeight = kg;   
    };

    // Private method for passing increased value. 
    var increaseEnergy = function( newVal ){
      canPull( newVal );
    };

    //  Private method for returning value of return canPullWeight,
    //  at any point of time, from the one and only existing instance.
    var pullCapacity = function(){
      return canPullWeight;
    };

    return {
      // returns increaseEnergy method which is a 
      // closure with access to private properties.
      increaseEnergy: increaseEnergy,
      getPullCapacity: pullCapacity
    };
  };

  return {
    // Method for creating instance of Person.
    getInstance: function(){
      // Condition checking existence of instance
      if(!personInstance){
          personInstance = createPerson();
      }
      // If instance already existing returning the same.
      return personInstance;
    }
  };
})( );

// Creating firstPerson instance.
var  firstPerson = Person.getInstance( );

// alerts default value 3.
alert(firstPerson.getPullCapacity());

// Creating secondPerson instance (Same instance is used)
var secondPerson = Person.getInstance();

// Same output. Alerts default value 3.
alert(secondPerson.getPullCapacity());

// Calling increaseEnergy Method of firstPerson with newVal as 20.
// Note: we are not going to call increaseEnergy method of secondPerson.
firstPerson.increaseEnergy( 20 );

// alerts new value which is 20.
alert(firstPerson.getPullCapacity());

// It also alerts new value which is 20, as same instance is used
alert(secondPerson.getPullCapacity());

Keep the following in mind when you are reviewing the above code:

  • There is one and only one instance existing at any point of time during execution of code.
  • firstPerson and secondPerson are using same instance of Person returned.
  • Manipulating the value of firstPerson is impacting secondPerson also and vice-versa.
  • More than one instance of Person class cannot be created because of condition check.

Singleton pattern can be used in the following cases:

  1. To have some properties to be initialized with some default values in the script.
  2. To have a single instance for a frequently accessed static value through out the script.
  3. Singleton pattern is also used for NameSpacing in javascript.
  4. Initializing database connection input parameters.
  5. Keeping package dependency list statically.
  6. Having single point of access for a frequently changing value, at any instant of time.

Linux Sysadmin Course Linux provides several powerful administrative tools and utilities which will help you to manage your systems effectively. If you don’t know what these tools are and how to use them, you could be spending lot of time trying to perform even the basic administrative tasks. The focus of this course is to help you understand system administration tools, which will help you to become an effective Linux system administrator.
Get the Linux Sysadmin Course Now!

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

{ 5 comments… read them below or add one }

1 Renga June 11, 2014 at 6:28 am

When i executing the above script, i am getting blank alerts.

2 Anand June 11, 2014 at 8:43 am

Looks like there is an error/typo in the 1st line of code

var Person = (function()

should be

var Person = function()

3 Luke Issac June 11, 2014 at 9:28 pm

@Anand: Its not an error/typo. The function which you are pointing is a self invoking function.

@Renga: In the above script, there is method “pullCapacity”. Its is currently left blank. Its an typo here. This method should return the value of the property “canPullWeight”.
Please run the script and see the result which will clarify your doubts.

For your reference the correction is as follows:

var pullCapacity = function(){
return canPullWeight;
};

@Renga and Anand: You can the run the script using the link below and go through the comments in the code to clarify your doubts about how it is working.

http://jsfiddle.net/paZ4w/1/

4 Ramesh Natarajan June 11, 2014 at 11:12 pm

@Renga, @Anand,

A small correction was made to the code. It was missing this line: return canPullWeight;

Please try the code again. It should work now.

5 Robin June 12, 2014 at 12:21 am

Hi Anand, In 1st line of code, its not a typo/error. The function which you are pointing is a self invoking function. So the syntax goes like :
(function(){
// Logic goes here
})();

Its creating a closure there. Please refer the article “Javascript Closure” @thegeekstuff.com

Leave a Comment

Previous post:

Next post: