JavaScript design mode-singleton (singleton) mode

Source: Internet
Author: User

The singleton (singleton) pattern is known because it restricts the instantiation of a class to only one time, and in the case of a singleton pattern, a class can be created with a method to create a new instance of the class, and if the instance already exists, a reference to that object is simply returned. Singleton schemas are different from static classes (or objects) because we can defer their initialization, usually because it requires some information that may not be available during initialization, and they do not provide a convenient way to retrieve the previous reference code because it is neither an object, Nor is it a class returned by a single, but a struct, in JS, Singleton acts as a shared resource namespace, isolating code implementations from the global namespace, thus providing a single point of access to the function.

varMysingleton = ( function () {    //instance maintains a reference to the singleton    varInstacnce; function init() {        //Private methods and variablesFunciton Privatemethod () {//...}varPrivatevariable ="Private";varPrivaterandomnumber =Math. random ();/ * Define a singleton code here * /        return{//Public methods and variablesPublicmethod: function () {Console.log (' Hello World '); }, Publicproperty:' Test ', GetRandomNumber: function(){        returnPrivaterandomnumber;    }        }; }return{//Gets an instance of singleton, returns if it exists, does not exist create new instanceGetInstance: function () {            if(!instance)            {instance= init (); }returnInstance }    };}) ();/* Call the public method to get the instance: */Mysingleton. getinstance (). Publicmethod ();

Singleton Mode Applicability:

    1. When a class can have only one instance and the customer can access it from a well-known access point;
    2. When the only instance should be extensible by subclasses, and the customer should have no need to change the code to be able to use an extended instance.

      The difference between a static instance of a class and singleton: When Singleton can be implemented as a static instance, it can delay the build until a static instance is needed, without using resources and memory.
      If we have a static object that can be initialized directly, we need to ensure that the execution code order is always the same, and that it does not scale when we have a large number of source files.

In practice, the singleton pattern is useful when you really need an object in the system to coordinate other objects.

varSingletontester = ( function () {    //Parameters: A collection of parameters passed to the singleton     function Singleton(options) {        //Set the options variable to the received parameter or null (if not provided)options= options| | {};//Set the name parameter         This. Name =' Singletontester ';//Set the value of the Pointx         This. Pointx = Options.pointx | |6;//obtained from the received parameters, or set to the default value        //Set the value of the pointy         This. Pointy = Options.pointy | |Ten; }//Instance container    varInstance//Static variables and method simulations    var_static = {Name:' Singletontester ',//How to get instances        //Returns an instance of singletonGetInstance: function (options) {            if(Instance = = =undefined) {instance =NewSingleton (options); }returnInstance }    };return_static;}) ();varSingletontest = Singletontester.getinstance ({pointx:5}); Console.log (SINGLETONTEST.POINTX);//Output 5

The existence of Singleton often indicates that the modules in the system are either tightly coupled or that their logic is too scattered in multiple parts of the code base. Because of a series of problems: from hidden dependencies to the difficulty of creating multiple instances, the difficulty of underlying dependencies, and so on, singleton testing will be more troublesome

JavaScript design mode-singleton (singleton) mode

Related Article

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.