11
I would like to understand how objects created work by following the Pattern Singleton javascript design.
My main doubts refer to the methods and attributes of this object, where and how to create them and where and how to access them.
I read some articles even in English but I did not understand very well how to use Singleton correctly.
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
}
Objects are being instantiated in Function run
, my doubt on that would be, if I want to add a method stop
and an attribute status
to know if this object is in run
or stop
, how should I do this by following the Pattern design singleton
?
Reference:
A Beginner’s Guide to Design Patterns
Javascript Design Patterns: Singleton
Related: http://answall.com/questions/40603/singleton-em-javascript
– Sergio
Hello, @Rodrigo. Your doubts are not clear enough. You said they refer to such things, but what exactly are these doubts? Perhaps with examples it becomes clearer.
– Pablo Almeida
@Pablo added an example and tried to explain my doubt better, see if it’s better now
– RodrigoBorth
"The objects are being instantiated" the object, not "os" - the idea of Singleton is just that there is only one instance. This example uses Lazy instantiation, but could also not use, creating the object directly. Anyway, it is the function
createInstance
that you have to change, to modify your object Singleton. Instead ofnew Object("I am the instance")
, you put whatever you want your object to be. And the pattern ensures that it will be the same object whenever you usegetInstance
. P.S. didn’t understand this part: "know if this object is inrun
orstop
"– mgibsonbr
@mgibsonbr would only be the value of the status attribute, I think I’m beginning to understand...
– RodrigoBorth