This was asked in a recent discussion, but was not able to tackle it properly. However I answered it by giving example of Enum
but he was looking for some other way. Can you highlight the ways for which we can overcome above question?
Implement singleton pattern without using a private reference in java?
191 Views Asked by Bhargav Modi AtThere are 3 best solutions below

Short answer?
Using a private YourClass
constructor and a public YourClass
variable with eager instantiation
Long answer
https://en.wikipedia.org/wiki/Singleton_pattern
public class Singleton {
public static final Singleton INSTANCE = new Singleton();
//^ public variable
private Singleton() {}
//^ private constructor
}

It is a bad idea, but if you change the private
variable to a public
one, you will achieve your goal. You probably should declare the variable as final
as well to avoid surprises, but it is not strictly necessary, and doesn't make it a good idea (IMO).
For what it is worth, there is no way to implement a singleton that doesn't involve an explicit variable to hold the instance, or an enum
.
Here is what Bloch has to say on the tradeoff between the public and private variable approaches:
"One advantage of the factory-method approach is that it gives you the flexibility to change your mind about whether the class should be a singleton without changing its API. The factory method returns the sole instance but could easily be modified to return, say, a unique instance for each thread that invokes it. A second advantage, concerning generic types, is discussed in Item 27. Often neither of these advantages is relevant, and the final-field approach is simpler."
My argument is that knowing that you won't need to change your mind in the future involves a degree of prescience.
Or to put it another way, you can't know that: you can only predict that. And your prediction can be wrong. And if that prediction does turn out to be wrong, then you have to change every piece of code the accesses the singleton via the public variable.
Now if your codebase is small, then the amount of code you need to change is limited. However, if your codebase is large, or if it is not all yours to change, then this this kind of of mistake can have serious consequences.
That is why it is a bad idea.
This is how you would implement a
Singleton
with apublic
field :Further reading on the pros and cons of this approach :
Item 3 from Joshua Bloch's Effective Java.