JS Single case design mode

Source: Internet
Author: User

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; -}();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.