Part 3 of 6 · 1 min read
Three ways
Field, factory and enum.
EJ gives three ways. In all of them, the constructor is private.
The first has a public static final field.
public class Registry {
public static final Registry INSTANCE = new Registry();
private Registry() { }
}
The second keeps the field private and offers a static factory.
public class Registry {
private static final Registry INSTANCE = new Registry();
private Registry() { }
public static Registry getInstance() { return INSTANCE; }
}
The field version is simple and makes the singleton obvious from the API. The factory version lets the designer later change their mind, for example by returning one instance per thread, without changing the API. A method reference to it can also serve as a supplier. EJ says that unless one of those advantages matters, the field version is better.
Both have two weak points. A program with enough privilege can call the private constructor by reflection. And if the class is serializable, reading it back creates a second instance unless all fields are transient and a readResolve method returns the one instance.
The third way avoids both weak points: a single-element enum.
enum Config {
INSTANCE;
private int created = 0;
int next() { return ++created; }
}
Calling Config.INSTANCE.next() twice returns 1, then 2, because there is one object holding the counter. EJ calls the enum approach often the best way. It is shorter, gives serialization for free, and resists even reflection attacks. One limit: an enum cannot extend another class, though it can implement interfaces.
Check yourself:
1. What are the two weak points of the field and factory versions?
2. What does the enum version return on its second next() call?
3. What is the one limit of the enum approach?