Reputation: 65
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'.
What is the benefit of doing thing like this?
Upvotes: 0
Views: 228
Reputation: 8481
It looks like the Singleton pattern. 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.
Regarding this particular implementation, I would suggest a couple of fixes:
this.instance
in the static method should be MyClass.instance
insteadnew this(myString)
, myString
will be undefined
because non static variables cannot be referenced from the static contextmyString
public static Instance { ... }
should be a static method instead: public static instance() { ... }
Upvotes: 1