Reputation: 1601
Do classes annotated with @Singleton
have to follow the Singleton design pattern?
My guess is that they do not: it is not necessary to have a private constructor, and a static .instance()
method, but instead it is Guice that makes sure that only one instance of the class will be instantiated.
Upvotes: 2
Views: 1617
Reputation: 11123
The difference between a singleton in Guice and the regular singleton has to do with context.
When you're not using Guice you have to manage your singleton yourself. To ensure that there is only ever one instance created you have a private constructor, a static field and methods to access this instance (either a getter or making the field final). This means that the instance is a singleton in the context of the class loader. If you create another class loader and tell it to load your singleton class you can create a second instance.
When the singleton is managed by Guice we replace the private constructor and static field with the @Singleton
annotation, telling the injector that it should only ever create one instance of this class and use it anywhere it is requested. Since it is possible to have more than one injector simultaneously (either because you need two completely different contexts or because you're using child injectors) you must not prevent Guice from instantiating more than one instance of your class.
Additionally, since you should rely on Guice to provide the singleton everywhere it is required there is no need for a static field containing the singleton instance since it should never be accessed.
Upvotes: 3
Reputation: 32343
Not only are they not required to follow the Singleton pattern, they explicitly should not follow it.
A system that is properly set up with Guice should be creating as few of its own objects as possible, instead letting the framework do all of the object creation. Further, you do not want random classes in your system to be calling .instance()
on this static instance, and, finally, you do not want Guice to be creating a static reference in the Singleton class using .requestStaticInjection()
.
The right thing to do with your @Singleton
classes is to just have them be injected into the classes that need that particular dependency.
Upvotes: 8