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:
- var Singleton = WinJS.Class.define(function () {
- var instance;
-
- function createInstance() {
- var object = new Object("Ibrahim Ersoy");
- return object;
- }
-
-
- return {
- getInstance: function () {
- if (!instance) {
- instance = createInstance();
- }
- return instance;
- }
- };
-
- })();
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:
- var dev1 = Singleton.getInstance();
- var dev2 = Singleton.getInstance();
We've created 2 objects for checking if both are the same:
- console.log("Are you both Ibrahim Ersoy? " + (dev1 === dev2));
Finalize
Lets see the output it displays:
Full Code:
- var Singleton = WinJS.Class.define(function () {
- var instance;
-
- function createInstance() {
- var object = new Object("Ibrahim Ersoy");
- return object;
- }
-
-
- return {
- getInstance: function () {
- if (!instance) {
- instance = createInstance();
- }
- return instance;
- }
- };
-
- })();
-
- var dev1 = Singleton.getInstance();
- var dev2 = Singleton.getInstance();
-
- 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.