#设计模式
Review
- 2023-12-09 15:31
一、Introduction #
单例模式(Singleton Pattern)是一种创建型设计模式,可确保类只有一个实例并提供对该实例的全局访问点。 当您想要限制应用程序中类的实例数量并控制对单个共享实例的访问时,此模式特别有用。
// 方式1
class Singleton {
constructor() {
console.log('init');
this.instance = null;
}
static getInstance() {
if (!this.instance) {
this.instance = new Singleton();
}
return Singleton.instance;
}
}
const a = Singleton.getInstance();
const b = Singleton.getInstance();
console.log(a === b);// 方式2
let instance = null;
class Singleton {
constructor() {
if (!instance) {
instance = this;
// Your initialization code here
} else {
return instance;
}
}
// Your methods and properties here
}
// Usage
const singletonA = new Singleton();
const singletonB = new Singleton();
console.log(singletonA === singletonB); // Output: true (both variables reference the same instance)
实际用例 #
单例模式在各种场景中都很有用,包括:
- 管理配置设置:您可以使用单例来管理应用程序的配置设置,确保配置值有单一的真实来源。
- 记录器和错误处理:可以使用单例来维护集中式日志记录或错误处理机制,允许您合并日志条目或错误消息。
- 数据库连接:在处理数据库时,您可能希望使用单例来确保应用程序之间仅共享一个数据库连接,以最大限度地减少资源消耗。
- 缓存:实现单例来缓存常用数据可以通过维护单个缓存实例来帮助优化性能。
注意事项 #
虽然单例模式可能很有用,但明智地使用它也很重要。 过度使用单例模式可能会导致代码和全局状态紧密耦合,这可能会使您的应用程序更难以维护和测试。 因此,权衡利弊并在真正为代码库增加价值的地方应用该模式至关重要。