js单例模式

单例模式在各语言中较为常见,各种框架到处在使用单例模式,平常开发中也会接触到单例模式,以下为整理的较为完善的单例模式实现方案:

采用proxy代理,或者控制new的时机,通过调用特定的方法来new,new的时候判断是否已经new过,但此方法不能往原型上追加东西。

export function singleton(className) {
let ins;
// 通过代理,解决不能往原型追加方法问题
return new Proxy(className, {
construct(target, args) {
if (!ins) {
ins = new target(…args);
}
return ins;
}
})
// 此方法不能往原型追加方法
// return class {
// constructor(…args) {
// if (!ins) {
// ins = new className(…args);
// }
// return ins;
// }
// }
}

class Notice {

}
export default singleton(Notice);
const notice = new Notice();

当然,除上述方案外,还有其他方案,需Notice类内再写一个getInstance方法,方法内部即:
static _ins; //实例
getInstance(name) {
if (!this._ins) {
return this._ins = new Notice();
}
return this._ins;
}
这样的话,外部调用的时候,统一都不采用new,而是直接调用notice.getInstance()方法,但是此方法会有一个风险问题,即:如果大家协同开发时,不能保证大家都采用getInstance方法进行new,可能就会有小伙伴直接new了,进而导致了不是单列模式了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值