Singleton, which refers to an object with only one instance.
in the case of Singleton mode, the generation of a singleton class must ensure that only one instance exists, and many times the whole system only needs to have a global object in order to coordinate the behavior of the whole system. For example, in the whole system configuration file, the configuration data has a singleton object for unified reading and modification, other objects need to configure the data also unified through the Singleton object to obtain configuration data, so as to simplify configuration management in a complex environment.
Implementing one: Object literals
1 var singleton = {2 name:value,3 function() { 4 // This is method content 5 }6 };
Implementation two: internal judgment of the constructor function
1 functionConstruct () {2 //ensure that only a single case3 if(Construct.unique!==undefined) {4 returnConstruct.unique;5 }6 //other Code7 This. Name = "NYF";8 This. age= "24";9Construct.unique = This;Ten}
Implementation three: module mode
1 varSingleton =function(){2 //private variables and private functions3 varPrivatevariable = 10;4 5 functionprivatefunction () {6 //.......7 }8 9 return{TenPublicproperty:true, One APublicmethod:function(){ -privatevariable++; - returnprivatefunction (); the } - }; -}();
Implementation four: Enhanced module mode (singleton must be of some type)
1 varSingleton =function(){2 varPrivatevariable = 10;3 4 functionprivatefunction () {5 return false;6 }7 8 varObject =NewSomeType ();9 TenObject.publicproperty =true; One AObject.publicmethod =function(){ -privatevariable++; - returnprivatefunction (); the }; - - returnobject; -}();