I would like to understand how objects created following the singleton design pattern work in javascript.
My main doubts are about the methods and attributes of this object, where and how to create them, and where and how to access them.
I have read some articles even in English but I did not quite understand how to correctly use the singleton.
As an example I have this code:
Source: Dofactory - Singleton
var Singleton = (function () {
var instance;
function createInstance() {
var object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
function run() {
var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
alert("Same instance? " + (instance1 === instance2)); //retorna true
}
The objects are being instantiated in function run
, my question would be, if I want to add a method stop
and a status
attribute to know if this object is in run
or stop
, how should I do this following the design pattern singleton
?
Reference:
A Beginner's Guide to Design Patterns
JavaScript Design Patterns: Singleton