javascripttypescriptclassdesign-patterns

What kind of design pattern is this?


I was going through a TypeScript repository today and I found all the classes were implemented in this fashion:

export class ServiceClass {
  private static instance: ServiceClass;

  private constructor() {}

  public static Instance(): ServiceClass {
    if (!ServiceClass.instance) {
      ServiceClass.instance = new ServiceClass();
    }
    return ServiceClass.instance;
  }

  // public static ServiceMethod1

  // public static ServiceMethod2

  // public static ServiceMethod3
}

The class methods were used like new ServiceClass.Instance().ServiceMethod1().

What is the added benefit of having the Instance() method? How would it be different if just the service methods were present in the class, and to access them you could do something like this:

const obj = new ServiceClass();
obj.ServiceMethod1();

Is this some kind of design pattern?


Solution

  • This is the singleton pattern, it allows to access the same instance from everywhere without having to pass a reference.

    It's quite often considered an anti pattern as it introduces a global state and worsen the testability of the code base.