1. 系统中被唯一使用
2. 一个类只有一个实例
![](https://box.kancloud.cn/4acc40954113edeab0afe543cf256cef_591x454.png)
```
class SingleObject {
login() {
console.log('login...')
}
}
SingleObject.getInstance = (function () {
// 闭包
let instance
return function () {
if (!instance) {
instance = new SingleObject();
}
return instance
}
})()
// 测试
let obj1 = SingleObject.getInstance()
obj1.login()
let obj2 = SingleObject.getInstance()
obj2.login()
console.log(obj1 === obj2) //true,一样,所以叫单例模式
let obj3 = new SingleObject();
obj3.login();
console.log('obj1 === obj3',obj1===obj3) //false
```
```
class LoginForm {
constructor() {
this.state = 'hide'
}
show() {
if (this.state === 'show') {
alert('已经显示')
return
}
this.state = 'show'
console.log('登录框已显示')
}
hide() {
if (this.state === 'hide') {
alert('已经隐藏')
return
}
this.state = 'hide'
console.log('登录框已隐藏')
}
}
LoginForm.getInstance = (function () {
let instance
return function () {
if (!instance) {
instance = new LoginForm();
}
return instance
}
})()
// 一个页面中调用登录框
let login1 = LoginForm.getInstance()
login1.show()
// login1.hide()
// 另一个页面中调用登录框
let login2 = LoginForm.getInstance()
login2.show()
// 两者是否相等
console.log('login1 === login2', login1 === login2) //true
```