Definition of a singleton pattern: ensure an instance and provide global access.
Lazy Singleton Definition: objects are created only when they are needed.
In development, some objects often require only one, such as a thread pool, a global cache, a Window object in a browser, and so on.
A singleton in Java
The key is to use a variable to flag whether the object is currently created for a class.
Public classSingleton {PrivateSingleton () {}Private StaticSingleton single=NULL; //Static Factory Method Public StaticSingleton getinstance () {if(single =NULL) { single=NewSingleton (); } returnSingle ; }}
Such a singleton class has a certain "opacity", the user must know that this is a singleton class, cannot create an instance through new XXX, but need to use the Singleton.getinstance method to get the object.
A singleton pattern in JavaScript
According to the characteristics of the singleton mode: 1 Only one instance, 2) provide global access;
1) The Global object arguments in JavaScript undoubtedly conform to the characteristics of Singleton, but the disadvantage is that there will inevitably be a global pollution problem;
2) The following is a general approach to the implementation of a lazy single example
Document.addeventlistener ('domcontentloaded', function () {
Getsingle is a common method of creating a single casevargetsingle=function (FN) {varret; returnfunction () {returnret| | (Ret=fn.apply ( This, arguments)); }; }; //The following is an example of creating a unique landing floating window varCreateloginlayer=function () {varDiv=document.createelement ('Div'); Div.innerhtml='I'm landing on the floating window .'; Document.body.appendChild (DIV); returnDiv; }; varGetsingleloginlayer=Getsingle (Createloginlayer); vardiv1=Getsingleloginlayer (); varDiv2=Getsingleloginlayer (); Console.log (Div1===DIV2);//Output True},false);
JavaScript Design Pattern Learning four--singleton mode