Tabachi Harada
Tabachi Harada

Reputation: 65

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'.

What is the benefit of doing thing like this?

Upvotes: 0

Views: 228

Answers (1)

Kirill Simonov
Kirill Simonov

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 instead
  • in the following call new this(myString), myString will be undefined because non static variables cannot be referenced from the static context
  • there is no way to set myString
  • public static Instance { ... } should be a static method instead: public static instance() { ... }

Upvotes: 1

Related Questions