vendredi 10 juin 2022

Is there a common pattern to instantiate a library class as a singleton and have the library able to access that instance internally?

Say I have a library project which provides a class MyService.

I'd like clients to be able to instantiate MyService as a singleton and at the same time, I'd like the library to be able to access that singleton internally.

Now I can do the standard MyService.getInstance() sort of thing, but that doesn't lead to a very testable code if my library has MyService.getInstance() calls all over the place.

Perhaps any classes in the library that need an instance of MyService can take in MyService as a constructor parameter:

class MyTestableClass(val myService: MyService) {
    // Now this class can be unit tested with a mock/fake MyService
}

But at some higher level in the library I'm still going to have to pass MyService.getInstance() to this class.

Is there a standard pattern to accomplish this? Basically I want the client to be able to instantiate MyService as a singleton and also have the library able to access that instance internally, while having the ability to swap out the singleton instance with a mock/fake for unit testing.

Aucun commentaire:

Enregistrer un commentaire