设计模式之单例模式

1. 单例模式
也就是整个项目中,就只有这一个实例,但是这个单例模式不透明,我们不知道
调用getInstance的方法


class Animal {
    static instance;
    static getInstance() {
        // 如果不存在就创建一个 实例对象
        if(!Animal.instance) {
            Animal.instance = new Animal();
        }
        // 如果 存在就把这个实例 返回出去
        return Animal.instance;
    }
}

const a1 = Animal.getInstance();
const a2 = Animal.getInstance();
console.log(a1 === a2);  // true

2.封装单例模式
这个样子 我们就可以创建不同的种类了,但是每个的实例都是指向自己的,从而得到了扩展

function Animal () {

}

function Coffee () {

}

Animal.prototype.hello = function () {
    console.log("hello");
}


Coffee.prototype.hello = function () {
    console.log("hello");
}

let createInstance = function (Constructor) {
    let instance;
    return function() {
        if(!instance) {
            Constructor.apply(this, arguments);
            // 这个是把 this.__proto__ = Constructor.prototype,这个样子 就不会导致指向错误
            Object.setPrototypeOf(this, Constructor.prototype);
            // 这个是把当前的 this原型赋值给他, 这个样子就可以判断,
            // 虽然是不同的种类 但是种类的实例都是指向自己的
            instance = this;
        }
        return instance;
    }
}

let createAnimal = createInstance(Animal);
let a1 = new createAnimal();
let a2 = new createAnimal();
console.log(a1 === a2, "a");   // true a

let createCoffee = createInstance(Coffee);
let c1 = new createCoffee();
let c2 = new createCoffee();

console.log(c1 == c2, "c");  // true c

使用场景:
redux中的createStore 就是一个单例模式,在整个项目中,store实例都是只有一个实例

import createStore from "redux";

function reducer() {

}

let initState = {};

// 这个createStore 就是一个单例模式, 全局的store都是共享的
let store = createStore(reducer, initState);

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...