【ES6】使用Proxy实现单例模式

前言

由于JS没有private关键字,无法私有化构造器,所以下面代码无法限制:

javascript 复制代码
class Person {
  constructor() {
    console.log("Person created");
  }
}

const p1 = new Person();
const p2 = new Person();

console.log(p1 === p2); // false

实现

通过 Person.getInstance() 生成对象

javascript 复制代码
class Person {
  constructor() {
    console.log("Person created");
  }
  static _ins = null
  static getInstance() {
    if (!this._ins) {
      this._ins = new Person();
    }
    return this._ins;
  }
}

const p1 = Person.getInstance();
const p2 = Person.getInstance();

console.log(p1 === p2);

但是如果创建对象时使用new Person(),仍无法实现单例模式。

下面封装一个函数,把任何类传入,将其变为单例模式:

javascript 复制代码
function singleton(className) {
  let ins
  return class {
    constructor(...args) {
      if (!ins) {
        ins = new className(...args)
      }
      return ins
    }
  }
}
class Person {
  constructor() {
    console.log("Person created");
  }
}

// const p1 = new Person();
// const p2 = new Person();
const SingletonPerson = singleton(Person);
const p1 = new SingletonPerson();
const p2 = new SingletonPerson();

console.log(p1 === p2);

但是这种实现方式仍有缺陷,并不能添加原型方法

javascript 复制代码
const SingletonPerson = singleton(Person);
const p1 = new SingletonPerson();
const p2 = new SingletonPerson();
SingletonPerson.prototype.say = function () {
  console.log("hello world");
}
p1.say();

下面使用 Proxy 实现,不返回一个新类,而是代理,给代理对象的原型上加方法等于直接给该对象的原型加方法。

javascript 复制代码
function singleton(className) {
  let ins
  return new Proxy(className, {
    construct(target, args) {
      if (!ins) {
        ins = new target(...args);
      }
      return ins
    }
  })
}
class Person {
  constructor() {
    console.log("Person created");
  }
}
const SingletonPerson = singleton(Person);
const p1 = new SingletonPerson();
const p2 = new SingletonPerson();
SingletonPerson.prototype.say = function () {
  console.log("hello world");
}
p1.say();
console.log(p1 === p2);
相关推荐
网络点点滴几秒前
标签的ref属性
前端·javascript·vue.js
Cobyte1 小时前
17. Vue3 业务组件库按需加载的实现原理
前端·javascript·vue.js
谢尔登2 小时前
原型理解从入门到精通
开发语言·javascript·原型模式
粥里有勺糖2 小时前
视野修炼-技术周刊第127期 | Valdi
前端·javascript·github
码上成长2 小时前
Vue Router 3 升级 4:写法、坑点、兼容一次讲透
前端·javascript·vue.js
qq_398586544 小时前
浏览器中内嵌一个浏览器
前端·javascript·css·css3
*小雪5 小时前
uniapp写H5授权登录及分享,返回到目标页面
开发语言·javascript·uni-app
性野喜悲5 小时前
ts+uniapp小程序时间日期选择框(分开选择)
前端·javascript·vue.js
你不是我我5 小时前
【Java 开发日记】SQL 语句左连接右连接内连接如何使用,区别是什么?
java·javascript·数据库
一壶浊酒..6 小时前
请求签名(Request Signature)
javascript