Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading