⑤独一无二-单例模式

单例模式

确保一类只有一个实例,并提供全局访问点

这个模式很简单,目的就是让类只能被实例化一次,思路就是如果没有被实例化就实例化类,如果已经实例化直接返回实例化的对象。

因为在 JS 中,类的静态方法不能访问类的实例属性,所以考虑把类的实例缓存在类的静态属性中。

1
2
3
4
5
6
7
8
9
10
class Singleton {
static instance: InstanceType<typeof Singleton> | null = null;
static getInstance() {
if (!this.instance) {
return (this.instance = new Singleton());
} else {
return this.instance;
}
}
}

如果不使用 ES6 class 实现,可以使用函数的方式配合模块化规范,导出创建方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
interface ISingleton {}
interface ISingletonConstructor {
new (): ISingleton;
}
class Singleton implements ISingleton {
constructor() {}
}

let getSingletonInstance = (Singleton: ISingletonConstructor): ISingleton => {
let instance: ISingleton = new Singleton();
getSingletonInstance = (Singleton?: ISingletonConstructor): ISingleton =>
instance;
return instance;
};

export { getSingletonInstance };
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2025 SunZhiqi

此时无声胜有声!

支付宝
微信