The basic structure of a single case pattern:
Copy Code code as follows:
Mynamespace.singleton = function () {
return {};
}();
Like what:
Copy Code code as follows:
Mynamespace.singleton = (function () {
return {//public members.
Publicattribute1:true,
Publicattribute2:10,
Publicmethod1:function () {
...
},
Publicmethod2:function (args) {
...
}
};
})();
However, the above Singleton is already established when the code is loaded, how to delay loading? Imagine how to implement a single example in C #: Use the following pattern:
Copy Code code as follows:
Mynamespace.singleton = (function () {
function constructor () {//All of the ' normal singleton code goes here.
...
}
return {
Getinstance:function () {
Control code goes here.
}
}
})();
Specifically, the code that creates the singleton is put into the constructor, and then instantiated at the first call:
The complete code is as follows:
Copy Code code as follows:
Mynamespace.singleton = (function () {
var uniqueinstance;//Private ATT Ribute 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;
}
}
}) ();