定义
Ensure a class has only one instance,and provide a global point of access to it.
(确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例)
应用(例子)
//懒汉式单例又称惰性单例,前端不考虑,如果是后端可能会考虑高并发的情况下出现多个实例
class LazySingle {
private static _instance = null;
//限制产生多个对象
private constructor(){
}
//获得实例对象
public static getInstance():LazySingle{
if(!this._instance){
this._instance = new LazySingle();
}
return this._instance;
}
}
//饿汉式单例
class HungrySingle{
private static _instance:HungrySingle = new HungrySingle();
//限制产生多个对象
private constructor(){
}
//获得实例对象
public static getInstance():HungrySingle{
return this._instance;
}
}
好处
- 减少内存开支
- 减少性能开支,如配置需要频繁读取的信息
- 避免对资源的多重占用,造成不必要的麻烦
- 优化和共享资源访问,比如组件状态管理,我会创建一个单例来存状态信息(比如说左侧list选中那个)