什么是单例模式
- 定义
一个类只返回一个实例,一般会提供一个访问点可以访问到这个实例。也是说当你重复使用该类时,都返回的时同一个实例。 - 优点
在js中单例模式可以用来划分命名空间;更优雅的组织代码方式以便于后期开发和维护;由于每次都返回的是同一个实例,因此也节省了内存空间
单例模式在es5及es6中的应用
es5中的使用
其实在es5中我们经常使用单例这种模式,最常见的就是对象字面量
var singleton = {
name: 'singleton',
getName: function () {
return this.name
},
setName: function (newName) {
this.name = newName
}
}
然后我可以方便的通过singleton这个对象方便的调用其属性和方法。es5之前并没有模块管理这个概念,单例模式更多的是用于对命名空间的管理上,以便于隔离代码,防止跟其他人代码冲突。典型的如下面代码:
var singleton = (function () {
var instance = null
function User (name, age, sex) {
this.name = name
this.age = age
this.sex = sex
}
return {
getInstance: function (name, age, sex) {
if (!instance) {
instance = new User(name, age, sex);
}
return instance
}
}
})()
下面的例子在es5代码中也会经常用到
var singleton = (function () {
// dom操作
var dom = function () {}
// ajax请求
var fetchData = function () {}
return {
dom: dom,
ajax: ajax
}
})()
es6中使用
在es6中创建单例模式
class Singleton {
constructor (name, age, sex) {
if (!Singleton.instance) {
this.name = name
this.age = age
this.sex = sex
Singleton.instance = this
}
return Singleton.instance
}
}
我们可以使用静态反法来进行优化
class Singleton {
constructor (name, age, sex) {
this.name = name
this.age = age
this.sex = sex
}
static getInstance (name, age, sex) {
if (!this.instance) {
return this.instance = new Singleton(name, age, sex)
}
return this.getInstance
}
}