[英]Creating an instance of a class to call static methods
I recently came across some code which looks something like this,我最近遇到了一些看起来像这样的代码,
class MyClass {
private static instance: MyClass;
private myString: string;
public static Instance(myString) {
if (!this.instance) {
this.instance = new this(myString);
}
return this.instance;
}
private constructor(myString: string) {
this.myString = myString;
}
public getMyString() {
console.log(this.myString);
}
}
My question is, what is the need to do something like this?我的问题是,有什么需要做这样的事情? Why would a person create an instance like this, instead of creating an instance of the class 'the normal way'.
为什么一个人会创建这样的实例,而不是创建 class '正常方式'的实例。
What is the benefit of doing thing like this?做这样的事情有什么好处?
It looks like the Singleton pattern .它看起来像Singleton 模式。 This pattern is used to ensure that a class has only one instance: the constructor is private, so it cannot be used from the outside of the class.
此模式用于确保 class 只有一个实例:构造函数是私有的,因此不能从 class 外部使用。
Regarding this particular implementation, I would suggest a couple of fixes:关于这个特定的实现,我建议几个修复:
this.instance
in the static method should be MyClass.instance
instead this.instance
方法中的 this.instance 应该是MyClass.instance
new this(myString)
, myString
will be undefined
because non static variables cannot be referenced from the static contextnew this(myString)
中, myString
将undefined
,因为无法从 static 上下文引用非 static 变量myString
myString
public static Instance {... }
should be a static method instead: public static instance() {... }
public static Instance {... }
应该是 static 方法: public static instance() {... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.