我了解到我们应该避免使用Singleton。我想知道是否以这种方式开发模块,我是否正在做Singleton?
class MyClass{
}
export default new MyClass();
因为每次加载模块,我都会得到相同的实例,不是吗?
谢谢
答案 0 :(得分:0)
不是Singleton,请查看示例
class SingletonClass {
private static _instance:SingletonClass = new SingletonClass();
constructor() {
if(SingletonClass._instance){
throw new Error("Error: Instantiation failed: Use SingletonClass.getInstance() instead of new.");
}
SingletonClass._instance = this;
}
public static getInstance():SingletonClass
{
return SingletonClass._instance;
}
}
https://codebelt.github.io/blog/typescript/typescript-singleton-pattern/
答案 1 :(得分:0)
让我们看一个单例的例子。
假设我有一个名为 Accounting Department 的类,而在现实生活中,只有一个 Accounting Department。因此,我们只需要一个实例。
class AccountingDepartment {
private static accountingDepartment: AccountingDepartment;
private id: number;
private name: string;
static getInstance(): AccountingDepartment {
if (this.accountingDepartment) {
return this.accountingDepartment;
} else {
this.accountingDepartment = new AccountingDepartment(2, 'AD');
return this.accountingDepartment;
}
}
private constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
const accounting = AccountingDepartment.getInstance();
const accounting1 = AccountingDepartment.getInstance();
如果您看到,accounting 和accounting1 都会在控制台中为您提供相同的对象。所以只创建了一个单例实例。
注意事项:
由于只创建了类的单一实例,这就是它是单例模式的原因。