Home > Blockchain >  What is the purpose of a `getInstance()` method?
What is the purpose of a `getInstance()` method?

Time:11-04

I am looking at a user service, my understanding is it's similar to a user service in Nest, but not really.

In it I see the following:

export class UsersService {
  private usersDao: UsersDao

  constructor() {
     this.usersDao = UsersDao.getInstance();
  }
}

static getInstance(): UsersService {
  if (!UsersService.instance) {
    UsersService.instance = new UsersService();
  }
  return UsersService.instance;
}

What is that getInstance() doing exactly? And why not just:

export class UsersService {

  constructor(private usersDao: UsersDao) {}
}

What is the goal of getInstance()?

CodePudding user response:

Usually this is part of the singleton pattern. Basically one class that, once instantiated, any subsequent classes will refer to that instance, rather than creating a fresh instance each time.

https://en.wikipedia.org/wiki/Singleton_pattern

Its useful for a class where something complex needs to happen when it is first constructed, but all following calls just need access to the properties.

I'd also like to mention that you can (in JavaScript specifically) export an instance, and all modules that import the module will have access to the same instance.

  • Related