PDA

View Full Version : Singleton Pattern



plalx
18 Apr 2010, 7:09 AM
This is not directly related to ExtJS, but after searching for a good Singleton pattern in JavaScript without any success, I tought I could provide my own implementation of it. According to Head First - Design Patterns, the Singleton pattern should also make use of lazy-instanciation, a point that most implementations I have seen seems to forget. Therefore:


/*
Pattern: Singleton
Description: Ensures one and only object is created.
*/

var Singleton = (function(){
var INSTANCE = null;

return {
getInstance:function(){
if (!INSTANCE)
INSTANCE = (function(){
var _name = 'Supertone';

return {
sayName:function(){
alert('I am ' + _name + '!');
}
}
})();
return INSTANCE;
}
}
})();