前端设计模式-单例模式

前言

概念: 确保一个类只有一个实例,并提供一个全局访问点来访问该实例。

使用场景:如vue的状态管理工具vuex

好处:符合路径唯一型和错误提示型两种开发规范,减少开发错误

实现方式:

ts版本

我们通过private关键字使这个类不能在外部new,否则报错。我们定义了一个方法获取这个实例,通过判断这个实例的存在来保证唯一性

typescript 复制代码
class Singleton {
    private static instance: Singleton;
    private constructor() { }
    // 通过静态方法获取实例
    public static getInstance() {
        if (!this.instance) {
            this.instance = new Singleton();
        }
        return this.instance;
    }
    public someBusinessLogic() {
        // ...
    }
}

// 直接new会报错
new Singleton(); // error:Constructor of class 'Singleton' is private and only accessible within the class declaration

// 通过定义的getInstance方法
console.log(Singleton.getInstance() === Singleton.getInstance()) // true,说明只创建了一个实例

js版本

版本1

好处:使用模块化避免内部直接new和通过静态方法new造成的不同实例产生

缺陷:存在通过原型的contructor函数重复new的隐患

javascript 复制代码
// single.js
class Singleton {
    constructor() {}
    static _instance;
    static getInstance() {
        if (!this._instance) {
            this._instance = new Singleton();
        }
        return this._instance;
    }
}
export default Singleton.getInstance();
​
// test.js
import stance from './single.js';
const a = new stance.constructor();
const b = new stance.constructor();
console.log(a === b); // false

我们通过模块化的方式直接导出类的getInstance方法,这里可以隐藏了这个类,别处使用的唯一实例,但是别人可能通过constructor(指向的就是这个类)取执行new,那么就绕过了我们写的判断

版本2(使用proxy完美保证单例模式)

javascript 复制代码
class Singleton {
    constructor() {}
}

// 封装一个函数,传入一个类,返回一个新的代理单例类
function toProxySingleton(className) {
    let instance;
    const proxyClass = new Proxy(className, {
        // 如果通过new调用,就会触发construct方法
        // 第一个参数是目标类,第二个参数是类里面的contructor的参数
        construct(target, argumentsList) {
            if (!instance) {
                console.log('new');
                instance = new className(...argumentsList);
                // 也可以通过Reflect.construct来创建实例
                // instance = Reflect.construct(target, argumentsList);
            } else {
                console.warn('instance already exists');
            }
            return instance;
        }
    });
    className.prototype.constructor = proxyClass; // 修复constructor指向
    return proxyClass;
}

const ProxySingle = toProxySingleton(Singleton);
console.log(new proxySingle() === new proxySingle()); // true,说明只创建了一个实例
console.log(new proxySingle() === new Singleton.constructor()) // true 使用contructor也不能创建第二个实例了
export default ProxySingle;

这时候我们在外部使用只需要引入这一个类去new即可,始终保证了一个类的实例的单一性

提醒:上述ts使用private实现的单例模式只能给我们语法上的提示,在编译为js的时候,js文件是没有报错效果的,仍然可以创造多个不同实例.

相关推荐
大飞pkz14 分钟前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
努力也学不会java14 分钟前
【设计模式】抽象工厂模式
java·设计模式·oracle·抽象工厂模式
青草地溪水旁21 分钟前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁22 分钟前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
Magnetic_h10 小时前
【iOS】设计模式复习
笔记·学习·ios·设计模式·objective-c·cocoa
A阳俊yi11 小时前
设计模式——结构型模式
设计模式
努力也学不会java18 小时前
【设计模式】状态模式
java·设计模式·状态模式
.豆鲨包18 小时前
【设计模式】单例模式
java·单例模式·设计模式
lpfasd12320 小时前
第2课:Agent系统架构与设计模式
设计模式·系统架构
青草地溪水旁1 天前
设计模式(C++)详解—原型模式(1)
c++·设计模式·原型模式