definition: Ensure that an object (class) has only one instance and provides a global access point to access it;
Implementation principle: The closure is used to maintain a reference to a local variable, which holds the only instance created for the first time;
Mainly used for: global caching, login floating window, etc. only need a single instance of the time;
One way to implement a single case pattern for a non-single-mode object (such as: Demo):
add a static method to the demo to implement the single example:
Demo.getsingle = (function () {
var demo = null;
return function (name) {
if (!demo) {
demo = new demo (name);
}
return demo;
}
}) ();
Usage:
Non-single case mode: var a = new Demo (' Peter ');
Single case mode:
var B1 = demo.getsingle (' Peter ');
var b2 = demo.getsingle (' Sufei ');
B1 = = B2;//true, all references are new Demo (' Peter ')
To implement a single example through a proxy class:
var Proxydemo = (function () {
var demo = null;
return function (name) {
if (!demo) {
demo = new demo (name);
}
return demo;
}
}) ();
Usage:
Non-single case mode: var a = new Demo (' Peter ');
Single case mode: var b = new Proxydemo (' Peter ');
two. Inert single case mode: Create the single case only when it is needed;
Here's how to create a generic, lazy single example:
var getsingle = function (foo) {
var single = null;
return function () {return Single
| | (single = Foo.apply (this,arguments));
}
;
Usage:
var createloginlayer = function () {
var frag = document.createdocumentfragment ();
var div = document.createelement (' div ');
Div.style.display = ' None ';
The following to add additional login elements to div
...
Document.body.appendChild (Frag.appendchild (Div));
return div;
}
var createsingleloginlayer = Getsingle (createloginlayer);
When the user clicks the button (id = ' lgbtn ') for the first time, it creates and displays the login window, and the Repeat-click button is not created repeatedly;
document.getElementById (' lgbtn '). onclick = function () {
var lg = Createsingleloginlayer ();
Lg.style.display = ' block ';
}
A computed result of a cached function, such as a sequence that computes a number
The following is not cached writing, very slow!
function foo (n) {
results = N < 2 n:foo (n-1) + foo (n-2);
return results;
}
Console.log (foo (40));//It must be counted for several seconds.
The following is the caching, the basic instantaneous results!
var cache = {};
function foo (n) {
if (!cache[n]) {
Cache[n] = n < 2? N:foo (n-1) + foo (n-2);
}
return cache[n];
}
Console.log (foo (100));
Better way to do it:
var foo = (function () {
var cache = {};
return function (n) {
if (!cache[n]) {
Cache[n] = n < 2? N:foo (n-1) + foo (n-2);
}
return cache[n];
}
();
Reference documents:
"JavaScript mode"
JavaScript design pattern and development practice
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.