Home > Web Front-end > JS Tutorial > js design pattern - the use of singleton pattern

js design pattern - the use of singleton pattern

php中世界最好的语言
Release: 2018-03-14 14:02:33
Original
2416 people have browsed it

This time I will bring you the js design pattern-The use of singleton mode, the use of js singleton modeWhat are the precautions, The following is a practical case, let’s take a look.

1. Concept:
In the eyes of traditional development engineers, the single-interest model ensures that each class has only one instance. When implementing, we first determine whether the instance exists. If it exists, return it directly. If it does not exist, create it and return it. This ensures that there is only one instance object for each class. In JavaScript, a singleton serves as a provider of a namespace, providing a unique access point to access objects globally. 123
2. Functions and precautions:
Function: 1. Inter-module communication
2. Only one object of a certain class can exist in the system
3. Protect your own attributes and Method
Notes: 1. Pay attention to the use of this
2. Closures can easily cause memory leaks
3. Pay attention to the use of new when using inheritance.

3. The simplest way to implement
is to use object literals, which can contain a large number of properties and methods.

var firstObject = {
    property1: "something",
    property2: "something else",
    method1: function () {
        console.log('hello web!');
    }
};
Copy after login

If you want to extend this object, we can provide our own private members, and then we encapsulate these variable and function declarations inside it through closures. We can implement private or public methods. Let's look at the following code again:

var firstObject= function () {
    /* 这里声明私有变量和方法 */
    var privateVariable = 'something private';    function showPrivate() {
        console.log(privateVariable);
    }    /* 公有变量和方法(可以访问私有变量和方法) */
    return {
        publicMethod: function () {
            showPrivate();
        },
        publicVar: 'the public can see this!'
    };
};var single = firstObject();
single.publicMethod();  // 输出 'something private'console.log(single.publicVar); // 输出 'the public can see this!'
Copy after login

If we want to initialize it only when it is used, how should we do it? In order to save resources, we can initialize these codes in another constructor, as follows:

var firstjObiect= (function () {
    var instantiated;    function init() {
        /*这里定义单例代码*/
        return {
            publicMethod: function () {
                console.log('hello world');
            },
            publicProperty: 'test'
        };
    }    return {
        getInstance: function () {
            if (!instantiated) {
                instantiated = init();
            }            return instantiated;
        }
    };
})();/*调用公有的方法来获取实例:*/firstjObiect.getInstance().publicMethod();
Copy after login

Let’s take a look at its usage scenarios. Singletons are generally used between systems. Communication coordination of various modes

var firstObjectTester = (function () {
    //参数:传递给单例的一个参数集合
    function Singleton(args) {
        //设置args变量为接收的参数或者为空(如果没有提供的话)
        var args = args || {};        //设置name参数
        this.name = 'SingletonTester';        //设置pointX的值
        this.pointX = args.pointX || 6; //从接收的参数里获取,或者设置为默认值
        //设置pointY的值
        this.pointY = args.pointY || 10;
    }    //实例容器
    var instance;    var _static = {
        name: 'SingletonTester',        //获取实例的方法
        //返回Singleton的实例
        getInstance: function (args) {
            if (instance === undefined) {
                instance = new Singleton(args);
            }            return instance;
        }
    };    return _static;
})();var singletonTest = firstObjectTester .getInstance({ pointX: 5 });
console.log(singletonTest.pointX); // 输出 5
Copy after login

Here is a link to an example of singleton mode implementation. Here is the link:
Solve the problem of converting Html to Txt and displaying Textarea data Txt to Html

The above method is mainly implemented, and there are other implementation methods (from Uncle Tom’s blog)
Method 1,

function Universe() {
    // 判断是否存在实例
    if (typeof Universe.instance === 'object') {        return Universe.instance;
    }    // 其它内容
    this.start_time = 0;    this.bang = "Big";    // 缓存
    Universe.instance = this;    // 隐式返回this}// 测试var uni = new Universe();var uni2 = new Universe();
console.log(uni === uni2); // true
Copy after login

Method 2,

function Universe() {
    // 缓存的实例
    var instance = this;    // 其它内容
    this.start_time = 0;    this.bang = "Big";    // 重写构造函数
    Universe = function () {
        return instance;
    };
}// 测试var uni = new Universe();var uni2 = new Universe();
uni.bang = "123";
console.log(uni === uni2); // trueconsole.log(uni2.bang); // 123
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

In-depth JavaScript DOM application

In-depth JavaScript timer

In-depth basic application of JavaScript

The above is the detailed content of js design pattern - the use of singleton pattern. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template