2

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()?

halfer
  • 19,824
  • 17
  • 99
  • 186
Daniel
  • 14,004
  • 16
  • 96
  • 156
  • The code is using the [Singleton pattern](https://www.dofactory.com/javascript/design-patterns/singleton) to limit the number of instances created by the code – blurfus Nov 03 '21 at 17:28
  • That `static getInstance(): UsersService` method definition seems to live outside of any `class`. Can you provide a complete code, please? – Bergi Nov 03 '21 at 19:28
  • Are you talking about `UsersDao.getInstance()` or about the other one (presumably `UsersService.getInstance`)? – Bergi Nov 03 '21 at 19:29
  • @blurfus …and it's not even a proper singleton pattern, since everyone can still do `new UsersService();`. – Bergi Nov 03 '21 at 19:33
  • @Bergi true, the constructor is not marked as private yet – blurfus Nov 03 '21 at 19:34
  • @Bergi, interesting point. What would a proper singleton pattern in this context look like? – Daniel Nov 03 '21 at 19:34
  • @blurfus, so you are suggesting that it still needs `private usersDao: UsersDao` inside the constructor argument list? – Daniel Nov 03 '21 at 19:36
  • @Daniel It would put the `if (instance) return instance` right inside the constructor. Or even better, it wouldn't use `class` syntax and constructors at all, just a export a single object literal. – Bergi Nov 03 '21 at 19:40
  • 1
    @Daniel, No, I mean the constructor itself can be marked as private - i.e. `private contructor() {...}` - see https://stackoverflow.com/a/40034649/600486 for a complete example – blurfus Nov 03 '21 at 19:40

1 Answers1

2

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Djave
  • 8,595
  • 8
  • 70
  • 124