Single case mode of JS design pattern

Source: Internet
Author: User

introduce

In the eyes of traditional development engineers, a single example is to ensure that a class has only one instance, the method of implementation is generally to determine whether the instance exists or not, if there is a direct return, if there is no existence on the creation and return, which ensures that a class has only one instance object. In JavaScript, a single instance acts as a namespace provider, providing a unique access point from the global namespace to access the object.

Body

In JavaScript, there are many ways to implement a single example, the simplest of which is to use the method of object literal, which can contain a large number of properties and methods:

var Mysingleton = {
    property1: "Something",
    property2: "Something Else",
    method1:function () {
        Console.log (' Hello World ');
    }
;

If you want to extend the object later, you can add your own private members and methods, and then use closures to encapsulate the variables and function declarations inside them. Exposes only the public members and methods you want to expose, the sample code is as follows:

var Mysingleton = function () {/

    * * Here declares private variables and methods * *
    var privatevariable = ' something private ';
    function Showprivate () {
        console.log (privatevariable);
    }

    /* Public variables and methods (access to private variables and methods)/return
    {
        publicmethod:function () {
            showprivate ()
        },
        Publicvar: ' The public can this! '
    };

var single = Mysingleton ();
Single.publicmethod ();  Output ' something private '
console.log (Single.publicvar);//output ' the public can ' and ' this! '

The code above is pretty good, but if we want to do it only when we're using it, how do we do it? To conserve resources, we can initialize the code in another constructor, as follows:

var Singleton = (function () {
    var instantiated;
    function init () {/
        * * Here defines a single example code/return
        {
            publicmethod:function () {
                console.log (' Hello World ');
            } ,
            publicproperty: ' Test '
        }

    return {
        getinstance:function () {
            if (!instantiated) {
                instantiated = init ();
            }
            Return instantiated
        }}
    ;
} ();

/* Call the public method to get the instance:/
singleton.getinstance (). Publicmethod ();

Know how to achieve a single example, but the single example used in what kind of scene is better. In fact, a single example is typically used in communication coordination between various modes of the system, and the following code is a single best practice:

var Singletontester = (function () {

    //parameter: A parameter collection
    function Singleton (args) that is passed to a single

        instance Set the args variable to receive the parameter or empty (if not provided)
        var args = args | | {};
        Set the name parameter
        this.name = ' singletontester ';
        Set Pointx value
        this.pointx = Args.pointx | | 6;//get from the received parameter, or set the
        value of the default//set pointy
        this.pointy = Args.pointy | | ;

    }

    Instance container
    var instance;

    var _static = {
        name: ' Singletontester ',

        //Get instance's method
        //Return singleton instance
        getinstance:function (args) {
            if (instance = = undefined) {
                instance = new Singleton (args);
            }
            return instance;
        }
    ;
    return _static;
}) ();

var singletontest = singletontester.getinstance ({pointx:5});

Summary

The

Here understands the use of the implementation of a single instance pattern to a single example pattern. However, there are many ways to implement a single case pattern, but from the perspective of the project, you need to be simple and achievable, but from the perspective of research, there is time to study other implementation methods and perhaps get more.

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.