This is probably a pretty dumb question, but earlier today I ran into some code where an external class was storing a reference to a Singleton class instance (in a private field), and was using this reference instead of getting the instance from the Singleton class every time.
At first it looked like bad design to me, because it adds a field to a class for nothing, but is there another reason why you shouldn't do this (or should do this)?
Small code example to illustrate:
enum SomeSingletonObject {
INSTANCE;
public void someMethod() {...}
}
class AnotherObject {
private SomeSingletonObject sso;
public AnotherObject() {
this.sso = SomeSingletonObject.INSTANCE;
}
public void someMethod() {
sso.someMethod();
// instead of
// SomeSingletonObject.INSTANCE.someMethod();
}
}
In this example, no, there is no benefit.
However, if you are using dependency injection where your class takes its dependencies as constructor arguments, passing in a singleton instance could be very useful, and in that case you would have no option but to store the reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With