微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

设计模式之单例模式

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);

原文地址:https://www.jb51.cc/wenti/3279955.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐