Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Guice @Singleton have to follow the Singleton design pattern?

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.

like image 369
Jeff Avatar asked Jan 20 '26 15:01

Jeff


1 Answers

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.

like image 120
durron597 Avatar answered Jan 23 '26 06:01

durron597