Simple Answer: Use enum.
public enum SimplySingleton {
INSTANCE;
public void doSomethingSimple() {
// Do something simple.
}
}
Detailed Answer:
The Singleton design pattern addresses all of these concerns. With the Singleton design pattern you can:
- Ensure that only one instance of a class is created.
- Provide a global point of access to the object.
- Allow multiple instances in the future without affecting a singleton class's clients.
According to Effective Java Reloaded, the most effective & right way to implement a serialization singleton class is to use an enum to maintain the instance.
Below is the code which explains how to use the above defined enum
SimplySingleton
.
public enum Magic {
INSTANCE;
private final String fooString = "Best way to implement Singleton";
public void doSingletonMagic() {
Magic.INSTANCE.doSomethingSimple();
System.out.println(fooString);
}
}
Enum
provide implicit support for thread safety and only one instance is guaranteed. This is also a good way to have singleton with minimum effort.
Hope this helps you.
Shishir