单例模式是一个类全局只能有一个实例,且需要访问者通过一个访问入口获取实例对象
ES6代码演示
// 定义一个类
class Single{
constructor(name){
this.name = name;
}
getName(){
console.log(this.name);
}
}
// 定义一个类的静态方法并自执行
Single.create = (function() {
let instance;
// 通过闭包使得外部instance不销毁
return function getInstance(name) {
// 实例存在即返回,不存在创建新实例并返回
if(!instance){
instance = new Single(name);
}
return instance;
}
})();
//创建对象进行测试
const s1 = Single.create('zhangsan');
const s2 = Single.create('lisi');
// 对象相同,均返回第一个创建的对象,行成单例
console.log(s1===s2); // true
s1.getName(); // zhangsan
s2.getName(); // zhangsan
应用场景
页面遮罩层,全局缓存等