Murat Mustafin
Murat Mustafin

Reputation: 1313

Play Framework dependency injection Object vs @Singleton Class

Play Framework 2.4 has support for Google Guice Dependency Injection

What is the advantage of using

@Singleton class A

instead of

object A

for singletons?

Upvotes: 4

Views: 918

Answers (1)

jazmit
jazmit

Reputation: 5410

I can see three advantages of using @Singleton class over object if A has no dependencies:

  1. If you wanted to test A, and declare it as @Singleton class you have the option of subclassing it to mock out some of the functions in your test, whereas this is not possible with an object.

  2. If you use object, it is very tempting for clients of A to reference it directly, leading to a strongly coupled system, but using @Singleton class forces them to think about where A is instantiated, probably leading to a more decoupled design.

  3. If you later change your mind, and allow multiple instances of A, the refactoring will be much easier to do if you chose to use @Singleton class.

If A has dependencies, however, using @Singleton class allows them to be dependency injected on construction, whereas with an object this is only possible if you declare the dependencies as mutable (eg: a var with getter/setter methods) .

Upvotes: 6

Related Questions