Reputation: 1313
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
Reputation: 5410
I can see three advantages of using @Singleton class
over object
if A has no dependencies:
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
.
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.
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