单例模式 Singleton

概述

单例模式的定义是:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

单例模式是一种常用的模式,有一些对象我们往往只需要一个,比如线程池、全局缓存、浏 览器中的 window 对象等。在 JavaScript开发中,单例模式的用途同样非常广泛。试想一下,当我们单击登录按钮的时候,页面中会出现一个登录浮窗,而这个登录浮窗是唯一的,无论单击多少次登录按钮,这个浮窗都只会被创建一次,那么这个登录浮窗就适合用单例模式来创建。

运用

单例 Me 类

class Me {
    constructor() {
        this.firstName = "Baptiste";
        this.lastName = "Vannesson";
    }   
    static getInstance() {
        if (!Me.instance) {
            // Static attribute which holds the unique instance of 'Me'
            Me.instance = new Me();
        }
        return Me.instance;
    }
}

return {
    getInstance() {
        return Me.getInstance();
    }
};

测试一下

let me = Me.getInstance(),
    meAgain = Me.getInstance();

if (me === meAgain) {
    console.log("OK");
} else {
    console.log("KO");
}

results matching ""

    No results matching ""