I haven't been busy with projects recently, so I rarely have time to read books. I usually like the language js. I have also read many advanced tutorials and feel that I am still quite passionate about the design model of js. This time I will review "JavaScript Design Patterns and Development Practice", which starts with a singleton pattern.
/** * pre singleton mode * Definition: Ensure that a class has only one instance and provides a global access point to access it * Application: Singleton pattern is a commonly used pattern. There are some objects we often only need one. * For example, thread pool, global cache, window objects in the browser, etc. */ //--------------singleton-01------------- /*Writing method 1*/ var Singleton = function(name){ = name; = null; }; = function(){ alert(); }; = function(){ if(!){ = new Singleton(name); } return ; }; var a = ("amy"); var b = ("ben"); alert(a === b); // ------------singleton-02---------------- /*Writing method 2*/ var Singleton = function(name){ = name; } = function(){ return ; } = (function(){ var instance = null; return function(name){ if(!instance){ instance = new Singleton(name); } return instance; } })(); var a = ("amy"); var b = ("ben"); alert(a === b); // ------------singleton03----------- /*Writing method 3*/ var Singleton = (function(){ var instance; return function(name){ if(instance){ return instance; } = name; instance = this; } })(); var a = new Singleton("amy"); var b = new Singleton("ben"); alert(a === b); //-----------------------------------------------------------------------------------------------------------------------------var getSingleton = function(fn) { var result; return function() { if(!result) { result = (this, arguments); } return result; } }; var getSingletonVip = (function() { var instance; return function(fn) { return instance || (instance = (this, arguments)); } })(); var createLoginUser = function() { var div = ("div"); = 'This is the login box'; (div); return div; }; var createInfoGrid = function() { var div = ("div"); = 'This is the list information box'; (div); return div; }; //--Execute singleton1var createUserDiv = getSingleton(createLoginUser); createUserDiv(); createUserDiv(); //--Execute singleton2getSingletonVip(createLoginUser); getSingletonVip(createLoginUser);
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.