单例模式
定义
保证一个类仅有一个实例,并提供一个访问它的全局访问点
作用
主要解决一个全局使用的类频繁地创建和销毁,占用内存
优点
- 在内存里只有一个实例,减少了内存的开销,尤其是频繁地创建和销毁实例
- 避免对资源的多重占用
实现
实现一个简单的单例模式只要将实例对象保存起来,下一次获取/创建对象的时候,直接返回之前创建的实例。
对比非单例模式:
function Person(name, age) {
this.name = name
this.age = age
}
let one = new Person('zll', 19)
let two = new Person('prays', 21)
console.log(one, two)
运行截图
将以上示例修改为单例模式
let Person = (function () {
let instance = null
return function (name, age) {
this.name = name
this.age = age
if (instance) {
return instance
}
return instance = this
}
})()
Person.prototype.sayHello = function () {
console.log(this.name)
}
let one = new Person('zll', 19)
let two = new Person('prays', 21)
one.sayHello()
two.sayHello()
console.log(one === two)
运行结果
使用代理来创建单例,因此来改变Person对象永远只是一个单例的问题
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.sayHello = function () {
console.log(this.name)
}
let PersonProxy = (function(){
let instance = null
return function (name,age){
if(instance){
return instance
}
return instance = new Person(name,age)
}
})()
let one = new PersonProxy('zll', 19)
let two = new PersonProxy('prays', 21)
one.sayHello()
two.sayHello()
console.log(one === two)
运行结果