The basic structure of the singleton pattern:
MyNamespace.Singleton = function () {
return {};
}();
For example:
MyNamespace.Singleton = (function() {
return { // Public members.
publicAttribute1: true,
publicAttribute2: 10,
publicMethod1: function() {
...
},
publicMethod2: function(args) {
...
}
};
})( );
However, the above Singleton has been created as soon as the code is loaded. How to delay loading? Imagine how to implement a singleton in C#:) Use the following pattern:
MyNamespace.Singleton = (function() {
function constructor() { // All of the normal singleton code goes here.
...
}
return {
getInstance: function() {
// Control code goes here.
}
}
})();
Specifically, create a singleton Put the code in the constructor and instantiate it when it is called for the first time:
The complete code is as follows:
MyNamespace.Singleton = (function() {
var uniqueInstance; // Private attribute that holds the single instance.
function constructor() { // All of the normal singleton code goes here.
...
}
return {
getInstance: function() {
if(!uniqueInstance) { // Instantiate only if the instance doesn't exist.
uniqueInstance = constructor();
}
return uniqueInstance;
}
}
})();