Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

单例模式 #7

Open
impeiran opened this issue Apr 30, 2020 · 0 comments
Open

单例模式 #7

impeiran opened this issue Apr 30, 2020 · 0 comments

Comments

@impeiran
Copy link
Owner

单例模式的定义:

保证一个类仅有一个实例,并提供一个访问它的全局访问点。

实现单例模式的常用做法:

  1. 使用一个私有属性作标识,存放已经创建的实例。
  2. 构造方法里进行判断:已有实例则返回,无则创建。
  3. 判断时需要考虑多线程异步的情况,保证线程资源的安全。

如果在前端领域里,就不必考虑多线程的情况了。比较经常用到单例的有DialogToast框,例如:用户登录弹框、单次奖品弹框。

针对上述的要点,用JS我们可以用闭包模拟私有属性,奉承单一职责的原则,可以构建一个工厂函数,用于将正常的类加工成单例模式的类。

function singleton (target) {
  let _instance = null

  const _wrapper = function singletoned () {
    if (_instance) {
      return _instance
    } else {
      const ins = Object.create(target.prototype)
      _instance = target.apply(ins, arguments) || ins
      return _instance
    }
  }

  return _wrapper
}

上述代码没有直接用new来创建实例,我们直接用方法模拟new的实现,这样就可以用传递动态参数。

使用方法:

class Target {
  constructor () {
    this.name = 'target' + Date.now()
  }

  say () {
    console.log(this.name)
  }
}

const SingleTarget = singleton(Target)

new SingleTarget().say()
new SingleTarget().say()
new SingleTarget().say()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant