Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason to keep a reference to a Singleton instance in another class in Java?

Tags:

java

singleton

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();
    }
}
like image 711
nbarraille Avatar asked Sep 16 '25 18:09

nbarraille


1 Answers

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.

like image 192
cdhowie Avatar answered Sep 18 '25 10:09

cdhowie