Definition: Ensure that an object (class) has only one instance and provides a global access point to access it;
Implementation principle: Use closures to maintain a reference to a local variable that holds the only instance created for the first time;
Mainly used for: global cache, login floating window, etc., when only a unique instance is needed;
1. Methods to implement singleton pattern for a non-singleton pattern object (such as Demo):
Add a static method to Demo to implement a singleton:
Demo.getSingle = (function(){ var demo = null; return function(name){ if(!demo){ demo = new Demo(name); } return demo; }})();usage:
Non-singleton mode: var a = new Demo('Peter');
Singleton mode:
var b1 = Demo.getSingle('Peter');var b2 = Demo.getSingle('Sufei');b1 === b2;//true, all reference new Demo('Peter')Implement singletons through proxy classes:
var ProxyDemo = (function(){ var demo = null; return function(name){ if(!demo){ demo = new Demo(name); } return demo; }})();usage:
Non-singleton mode: var a = new Demo('Peter');
Singleton mode: var b = new ProxyDemo('Peter');
2. Lazy singleton pattern: create the singleton only when needed;
Here is how to create a general lazy singleton:
var getSingle = function(foo){ var single = null; return function(){ return single || (single = foo.apply(this,arguments)); }};usage:
var createLoginLayer = function(){ var fragment = document.createDocumentFragment(); var div = document.createElement('div'); div.style.display = 'none'; //The following adds other login elements to the div... document.body.appendChild(frag.appendChild(div)); return div;}var createSingleLoginLayer = getSingle(createLoginLayer);//When the user clicks the button for the first time (id = When 'lgBtn'), create and display the login window. After repeated clicking of the button will not be created repeatedly; document.getElementById('lgBtn').onclick = function(){ var lg = createSingleLoginLayer(); lg.style.display = 'block';}Attachment: The calculation result of the cache function, such as calculating a sequence of numbers
The following is a way to write without cache, which is very slow!
function foo(n){ results = n < 2 ? n : foo(n - 1) + foo(n - 2); return results;}console.log(foo(40));//It has to be calculated for several secondsThe following is the cache writing method, and the results are basically instantly produced!
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 writing:
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]; };})();console.log(foo(100));References:
"JavaScript Mode"
"JavaScript Design Patterns and Development Practice"
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.