Definition of a singleton pattern: guarantees that a class has only one instance and provides a global access point to access it
Implement Singleton mode: Save an instance of a singleton pattern class, each time a new instance is created, there are no instances saved, and some return to the original instance.
Use a proxy to implement a singleton pattern: separate the "things" and "judge whether Singleton" codes that are actually done in the singleton mode (actually the same purpose as the following Getsingle, which is based on the implementation of the "class")
1 varProxysingletoncreatediv = (function(){2 3 varinstance;4 return function(HTML) {5 if( !instance) {6Instance =Newcreatediv (HTML);7 returninstance;8 }9 returninstance;Ten } One A})();
How to better use global variables:
- Using namespaces
- Encapsulating private variables with closures
General Lazy Singleton: the duties of "create instance object" and "manage a singleton" are placed in two methods respectively, which focus on the management of the Singleton Method-getsingle ().
1 varGetsingle =function(FN) {2 varresult;3 //The closure is formed here .4 return function(){5 //the contents of the parentheses do two things: Create an instance and store the instance in a closed package6 returnResult | | (Result = Fn.apply ( This, arguments));7 }8};
JavaScript Design patterns and Development Practices-4th chapter-Singleton mode