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

JavaScript设计模式(一):单例模式 #21

Open
yangrenmu opened this issue Apr 28, 2020 · 0 comments
Open

JavaScript设计模式(一):单例模式 #21

yangrenmu opened this issue Apr 28, 2020 · 0 comments
Labels

Comments

@yangrenmu
Copy link
Owner

定义

单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
这个可以类比浏览器中的 window 对象。有两个点需要注意:

  • 全局只有一个实例
  • 全局访问点唯一

简单来说就是,有个唯一的全局对象,供我们全局访问使用。

实现

const mySingleton = function (name) {
  this.name = name
  this.instance = null
}
mySingleton.prototype.getName = function () {
  return this.name
}
mySingleton.getInstance = function (name) {
  if (!this.instance) {
    this.instance = new mySingleton(name)
  }
  return this.instance
}
const a = mySingleton.getInstance('qi')
const b = mySingleton.getInstance('7')
console.log(a.getName(), b.getName()) // qi qi
console.log(a === b) // true

适用场景

主要用于维护一个全局实例对象,减少频繁创建和销毁实例以及内存的占用。如:弹窗,第三方库等。

if (window.libName) {
    return window.libName 
} else {
    window.libName = '...'
}


参考文章:
JavaScript 设计模式(一):单例模式

@yangrenmu yangrenmu added the mode label Apr 28, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant