Design Patterns in WinJS #6: Singleton

I've decided to write more OOP articles in WinJS library regarding the use of Design Patterns we all love! You can learn my previous parts:
Let's start with what this design pattern means.
 
What is Singleton Design Pattern?
 
Singleton is one of the most widely used design patterns in Javascript. It mainly creates only one instance of the object which lets you call it globally.
 
If you want to declare global variables across the js app,Singleton pattern is just for you
 
According to DoFactory,Singleton Pattern includes only one object:

 
Singleton object defines a function named getInstance() which returns you a unique instance.

getInstance implements another pattern named "Lazy Load".

What is Lazy Load?

Lazy Load checks if an object's instance has already been created if not it creates one immediately.This is called Lazy Load.
 
Since there's only one object, why don't we simply implement it?
 
Implementation
 
Create a Singleton object as follows:
  1. var Singleton = WinJS.Class.define(function () {  
  2.     var instance;  
  3.   
  4.     function createInstance() {  
  5.         var object = new Object("Ibrahim Ersoy");  
  6.         return object;  
  7.     }  
  8.   
  9.     //Lazy Load Section Start  
  10.     return {  
  11.         getInstance: function () {  
  12.             if (!instance) {  
  13.                 instance = createInstance();  
  14.             }  
  15.             return instance;  
  16.         }  
  17.     };  
  18.     //Lazy Load Section End  
  19. })();  
As previously stated,I also commented getInstance() using Lazy Load for instance checking.

We created an object named "Ibrahim Ersoy" and set its value to instance.
 
To call this pattern use code as follows: 
  1. var dev1 = Singleton.getInstance();  
  2. var dev2 = Singleton.getInstance();  
We've created 2 objects for checking if both are the same:
  1. console.log("Are you both Ibrahim Ersoy? " + (dev1 === dev2));  
Finalize

Lets see the output it displays:
 
 
 
Full Code:
  1. var Singleton = WinJS.Class.define(function () {  
  2.     var instance;  
  3.   
  4.     function createInstance() {  
  5.         var object = new Object("Ibrahim Ersoy");  
  6.         return object;  
  7.     }  
  8.   
  9.     //Lazy Load Section Start  
  10.     return {  
  11.         getInstance: function () {  
  12.             if (!instance) {  
  13.                 instance = createInstance();  
  14.             }  
  15.             return instance;  
  16.         }  
  17.     };  
  18.     //Lazy Load Section End  
  19. })();  
  20.   
  21.     var dev1 = Singleton.getInstance();  
  22.     var dev2 = Singleton.getInstance();  
  23.   
  24.     console.log("Are you both Ibrahim Ersoy? " + (dev1 === dev2));   
Why should you use it? 
 
It's easy to use and lets you access global variables, and it's used by most modern JS Libraries out there.


Similar Articles