Singletton Patter

The Singleton pattern is thus known because it restricts instantiation of a class to a single object.

Once you create the object no other object will ever be like that one.

Now depending on the scope you might have only created a local variable but if the user is outside the function then it's globally available to anyone.

The best example is JQuery.

Here is an example of Singletton taken from Addy Osmani:

[code lang="js"]
var mySingleton = (function () {

// Instance stores a reference to the Singleton
var instance;

function init() {

// Singleton

// Private methods and variables
function privateMethod(){
console.log( "I am private" );
}

var privateVariable = "Im also private";

var privateRandomNumber = Math.random();

return {

// Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
},

publicProperty: "I am also public",

getRandomNumber: function() {
return privateRandomNumber;
}

};

};

return {

// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function () {

if ( !instance ) {
instance = init();
}

return instance;
}

};

})();

var singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();
console.log( singleA.getRandomNumber() === singleB.getRandomNumber() ); // true

[/code]
The getInstance method is Singleton’s gatekeeper. It returns the one and only instance of the object while maintaining a private reference to it which is not accessible to the outside world.

Conclusion

Singletons reduce the need for global variables which is particularly important in JavaScript because it limits namespace pollution and associated risk of name collisions.

Σχόλια