alt text
Benjamin Thomson
Web & UX Designer

Drink A Coffee With Me Today

Loading...
Success!
Error!

Follow On Instagram

Mayank Gupta (+91-9711083089)
Menu
Close

Singleton Pattern

The intent of this article is to understand the concept of Singleton Pattern.


Singleton ensures that the number of instances of a particular type is restricted to only one.


This single instance is called as Singleton Object.



Features of Singleton Pattern:

1. Singleton Ensures that only one instance of a class exists

2. Create a shared piece of functionality which can be accessed accross different part of application.

3. Provides a global access to an instance of Object

4. Helps with the memory Managment by sharing a set of functionality accross other Objects

5. Provides Modularity where set of related features can represent an Entity.



Creational Design Pattern

Singleton Pattern exists as a part of Creational Design Pattern.


Creational patterns are the patterns which deals with creation of Object in the most efficient manner. The Creational logic is somehow hidden from the consumer, since the consumer of the object is not interested in "how an instance is created", he is only interested in consuming the Object Information.



Practical Scenerio:

Lets try to understand the usage of Singleton Pattern by taking a practical Problem:


Lets consider a scenerio where a user access an Application and once the user provide Login Information, User Info is fetched from the Database, This Information is required in different part of application.


While resolving the specified problem statement, we need to take care of following factors:


1. We should not create multiple instances of User Object


If we create multiple Object containing User data, each Object shall hold memory space, in an ideal design strategy, we should not consume access of Memory to store irrelevant data. If we are storing the same data in multiple Objects, it leads to Memory Loss. Therefore we need to ensure that the Information is stored in a single Object and there should be a single copy of that information.


2. The User Info should be accessible to all Places


The User Information should be available to entire Application. In order to ensure that the information is available to other components, we should ensure that the Object contains a global visibility. The User Object should be saved inside a namespace from where it can be accessible to others.


3. Object should contain set of Related Functionalities


The Object created should be such that the set of functionalities and variable declared should refer to some Related Entity. It would not be a good practice to associate functionalities and variables which are not a part of User Info. Object created should be such that they represent a fixed entity. "User" in our case. If the Object contains functionalities that are irrelevant to the user, then it a wrong practice.



Simplest Singleton Implementation:

Below is a simple Singleton Object declared using Object Literal.


As the Article progreses we shall come accross further complex implementation Of Singleton.


var Employee = {
  name: "Mayank",
  age: 28,
  designation: "Senior Software Developer",
  showDetails: function() {
    console.log(name + " " + designation);
  }
}

We shall now evaluate whether the basic intent of creating a singleton is fulfilled or not in above implementation


Lets look for the features of the above specified block of code:

1. Employee is created using a Object literal, therefore we cannot create Objects from it.

2. User Information is saved in Namespace "Employee", which can be accessed at other parts of application.

3. The Object "Employee" contains set of related functionalities and properties.

4. Creating a single Object that contains the User info, shall save memory space.



Different Implementation Of Singleton:

1. Using Object Literal:


Object Literal is set of comma seperated list of name-value pair wrapped inside curly brackets.

It uses the following Syntax Rules:

  • A colon seperated Name Value Pair
  • Comma seperate each name value pair from other.
  • No comma at the last name-value pair

The biggest advantage of using Object Literal is that we need not to call any constructor maintain correct order of arguments that need to be passed to the constructor function.


The simplest implementation of Singleton is using "Object Literal". Lets see a simple implementation:


var Employee = {
  name: "Mayank",
  age: 28,
  designation: "Senior Software Developer",
  showDetails: function() {
    console.log(name + " " + designation);
  }
}

This Object is a single copy of the information, which is refered by a namespace "Employee".

Set of related functionalities and variables are enclosed within a single block to form an entity


2. Using Module Pattern and IIFE:


We can use Module pattern to create a Singleton Function.

Module pattern can be defined as an anonymous function which is self invoked (IIFE) and return a set of related functionalities and properties, which will then be assigned to a Namespace (Object).

Now lets see the implementation of Singleton Pattern using IIFE:


var Employee = (function() {
  var name = "Mayank;
  var age = 28;
  var designation = "Senior Software Developer"
  var showDetails = function() {
    console.log(name + " " + desination);
  }

  return {
    name: name,
    age: age
    showdetails: showDetails
  }
}

var myName = Employee.name;
var myAge = Employee.age;

Employee.designation;  // This is error since designation property is not exposed

Employee.showDetails();

Here we can see the Implementation of Singleton Object using IIFE.

According to the implemenatation:

1. A closure is created with the set of related functionalities and Object

2. These set of related data is a part of function scope ie private to the Anonymous Function

3. Set of functionalities are exposed to the Employee Namespace using "return" keyword.

4. The Employee namespace shall now contain the returned properties and functionalities.


** Note: "designation" here is created as a private member inside IIFE, but the Object also exposes the "showDetails" function which need to access the "designation" variable. This function when accessed from outside the IIFE scope can still refer to the private member "designation". This is because of the concept called Closure.

We shall learn the concepts of closure in a seperate article, but for now we need to remember that closure is a property of a variable or a function to remember the enviroment in which it was created. Since the function requires the access to the variable "designation", the local enviroment in which the Object was created in remembered and hence we can still access the variable "designation".


3. More Complex Implementation of Singleton:

var Employee = (function() {

  var details = null;

  var getInstance = function() {
    if(details == null) {
      details = {
        name: "Mayank",
        age: 28
      }
    }
    return details;
  }

  return {
    getInstance: getInstance
  }
})();

var myEmployee = Employee.getInstance();

In the above specified implementation, we have created an IIFE, this anonymous function returns the "getInstance" function.

In the above implementation of Singleton, a closure is created using IIFE. "getInstance" refers to the "details" Object even when it is declared as private, "getInstance" shall have the access to "details" Object that was created inside the IIFE as private member.


When we invoke "getInstance" function on Employee Object, following happens:

1. Runtime checks to see if we have Oject defined with the name "details"

2. If the details object is null, it created initializes the Object for Details and return it from the function.

3. If the details is already initialized, it is returned.


**Note: In the above implementation of Singleton, a closure is created for the variable "details", so even when the variable is described as aprivate variable, it can still be accessed inside the publically exposed function "getInstance", when it is executesd from outside the Closure Scope.


Different Singleton Instantiation:

1. Lazy Instantiation

In Lazy Instatiation, the Singleton variable will not get the momory untill we call the function which is responsible for creating and returning the Singleton Object.


var Employee = (function() {

  var details = null;

  var getInstance = function() {
    if(details == null) {
      details = {
        name: "Mayank",
        age: 28
      }
    }
    return details;
  }

  return {
    getInstance: getInstance
  }
})();

var myEmployee = Employee.getInstance();

In this Example, the IIFE contains a singleton Object "details", the details object shall not be assigned memory untill the function "getInstance" is called, this is called Lazy Instantiation.


The advantage of using this pattern:

1. Object shall not consume space untill the function call is made

This ensures that the Object shall be instantiated with memory only when it is required by the user.


2. Early Instantiation


In case of Early Instantiation, the singleton object is available to the user while initialization itself, the Singleton shall consume memory even if it is not used.


var Employee = (function() {
  var name = "Mayank;
  var age = 28;
  var designation = "Senior Software Developer"
  var showDetails = function() {
    console.log(name + " " + desination);
  }

  return {
    name: name,
    age: age
    showdetails: showDetails
  }
}

In this Example, the IIFE shall return set of functionalities and properties from the function. Here once the IIFE is executed, the singleton shall hold the properties and functionalities returned from the function invokation.



Conclusion:

Hope that the article was able to explain you the concept of Singleton Objects.

Please provide your reviews regarding the Article, this shall help me learn more and present some better articles in the near future. Thanks.





{{Count}} Comments

{{comment.user}}

{{comment.message}}

{{comment.date.substring(0, 10)}}

Leave A Comment

;