× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

JavaScript: The Singleton Pattern

Nishant
May 13, 2015
<p>The singleton pattern is the most commonly used design pattern and one that you will probably is more than any others. It provides a great way to wrap code into logical unit that can be accessed through a single variable.<br> The Singleton design pattern is used when only one instance of object is needed throughout the lifetime of an application. <br> <br> In JavaScript there is different way to achieve singleton object than any other object oriented supported language (Java, C++). In JavaScript Singleton pattern have many uses, they can be used for Namespace, which reduce the number of global variables in your page (Prevent from polluting global space), Organizing code in a consistent manner, which increase the readability and maintainability of your pages.<br> <br> There are two important point in the traditional definition of Singleton pattern</p> <ul> <li>There should be only one instance allowed for a class and</li> <li>We should allow global point of access to that single instance</li> </ul> <p><strong>Let me define singleton pattern in JavaScript context:</strong></p> <blockquote> <p><em>It is an object that is used to create namespace and group together a related set of methods and attributes (encapsulation) and if we allow to instantiate than it can be instantiate only once.</em></p> </blockquote> <p><span style="background-color:rgb(255, 255, 255); color:rgb(77, 79, 81)">In JavaScript we can create singleton though object literal, However there are some another way but that I will cover in next post.</span><br> <br> <span style="background-color:rgb(255, 255, 255); color:rgb(77, 79, 81)">A singleton object consists of two parts: The object itself, containing the members (Both methods and attributes) within it, and global variable used to access it. The variable is global so that object can be accessed anywhere in the page, this is key feature of the singleton pattern.</span><br> <br> <strong>JavaScript: A Singleton as a Namespace</strong><br> <br> <span style="background-color:rgb(255, 255, 255); color:rgb(77, 79, 81)">As I have already stated above that singleton can be used to declare Namespace in JavaScript. Namespace is a large part of responsible programming in JavaScript. Because everything can be overwritten, and it is very easy to wipe out variable by mistake or a function, or even a class without even knowing it.</span></p> <p><span style="background-color:rgb(255, 255, 255); color:rgb(0, 0, 0)">A common example which happen frequently when you are working with another team member parallel,</span></p> <p> </p> <pre><code class="language-javascript">/* Declare globally */ function findUserName(id){ } /* Later in the page another programmer added code */ var findUserName = $('#user_list'); /* You are trying to call :( */ console.log(findUserName());</code></pre> <p>One of the best way to prevent accidentally overwriting variable is to namespace your code within a singleton object.</p> <pre><code class="language-javascript">/* Using Namespace */ var MyNameSpace = { findUserName : function(id){ }, // Other methods and attribute go here as well } /* Later in the page another programmer added code */ var findUserName = $('#user_list'); /* You are trying to call and you make this time workable */ console.log(MyNameSpace.findUserName());</code></pre> <h2 style="font-style:italic;"><strong>Singleton Design Pattern Implementation:</strong></h2> <pre><code class="language-javascript">/* Lazy Instantiation skeleton for a singleton pattern */ var MyNameSpace = {}; MyNameSpace.Singleton = (function(){ // Private attribute that holds the single instance var singletonInstance; // All of the normal code goes here function constructor(){ // Private members var privateVar1 = "Nishant"; var privateVar2 = [1,2,3,4,5]; function privateMethod1(){ // code stuff } function privateMethod1(){ // code stuff } return { attribute1 : "Nishant", publicMethod: function(){ alert("Nishant");// some code logic } } } return { // public method ( Global access point to Singleton object) getInstance: function(){ //instance already exist then return if(!singletonInstance){ singletonInstance = constructor(); } return singletonInstance; } } } })(); // getting access of publicMethod console.log(MyNamespace.Singleton.getInstance().publicMethod());</code></pre> <p>The singleton implemented above is easy to understand. The singleton class maintains a static reference to the lone singleton instance and return that reference from the static getInstance() method.</p>
comments powered by Disqus