Detailed explanation of the JavaScript design mode in singleton mode and the javascript Design Mode
Recently, my project is not very busy. It is rare to have time to read books. I usually like the js language. I have also read many advanced tutorials and feel that I am still keen on js design patterns. This time, I review the JavaScript design mode and development practice, which begins with the singleton mode.
/*** Pre Singleton mode ** definition: ensure that a class has only one instance and provides a global access point to it. * Application: Singleton mode is a common mode, there are some objects that we usually only need, * such as the thread pool, global cache, and window objects in the browser. * // -------------- Singleton-01 -------------/* write 1 */var Singleton = function (name) {this. name = name; this. instance = null;}; Singleton. prototype. getName = function () {alert (this. name) ;}; Singleton. getInstance = function () {if (! This. instance) {this. instance = new Singleton (name);} return this. instance;}; var a = Singleton. getInstance ("amy"); var B = Singleton. getInstance ("ben"); alert (a = B); // ------------ singleton-02 ----------------/* write 2 */var Singleton = function (name) {this. name = name;} Singleton. prototype. getName = function () {return this. name;} Singleton. getInstance = (function () {var instance = null; return function (Name) {if (! Instance) {instance = new Singleton (name) ;}return instance ;}) (); var a = Singleton. getInstance ("amy"); var B = Singleton. getInstance ("ben"); alert (a = B); // ------------ singleton03 -----------/* write 3 */var Singleton = (function () {var instance; return function (name) {if (instance) {return instance;} this. name = name; instance = this ;}}) (); var a = new Singleton ("amy"); var B = new Singleton ("ben"); al Ert (a = B); // ---------------- example ----------------- var getSingleton = function (fn) {var result; return function () {if (! Result) {result = fn. apply (this, arguments) ;}return result ;}; var getSingletonVip = (function () {var instance; return function (fn) {return instance | (instance = fn. apply (this, arguments) ;}} (); var createLoginUser = function () {var div = document. createElement ("div"); div. innerHTML = 'this is the logon box'; document. body. appendChild (div); return div ;}; var createInfoGrid = function () {var div = document. createElement ("div"); div. innerHTML = 'this is the list information box '; document. body. appendChild (div); return div ;}; // -- run singleton1 var createUserDiv = getSingleton (createLoginUser); createUserDiv (); // -- run singleton2getSingletonVip (createLoginUser ); getSingletonVip (createLoginUser );
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.