The Singleton mode can be written in many ways. A good article is recommended.
Http://devbean.blog.51cto.com/448512/203501
After reading the above article, you can take a look at my Singleton implementation from objective Java.
1. Simplest Singleton mode implementation
//Singleton with final field - page 10public class Elvis {public static final Elvis INSTANCE = new Elvis();private Elvis() {// ...}// ... // Remainder omittedpublic static void main(String[] args) {System.out.println(Elvis.INSTANCE);}}
2. Implement the singleton mode using the static factory Method
//Singleton with static factorypublic class Elvis {private static final Elvis INSTANCE = new Elvis();private Elvis() {// ...}public static Elvis getInstance() {return INSTANCE;}// ... // Remainder omittedpublic static void main(String[] args) {System.out.println(Elvis.INSTANCE);}}
The implementation differences between the two methods are explained below
3. Implement Singleton mode for static internal classes
/** * When the getInstance method is invoked for the first time, it reads * SingletonHolder.uniqueInstance for the first time, causing the * SingletonHolder class to get initialized.The beauty of this idiom is that the * getInstance method is not synchronized and performs only a field access, so * lazy initialization adds practically nothing to the cost of access. A moder * VM will synchronize field access only to initialize the class.Once the class * is initialized, the VM will patch the code so that subsequent access to the * field does not involve any testing or synchronization. * * @author mark * */public class Singleton {// an inner class holder the uniqueInstance.private static class SingletonHolder {static final Singleton uniqueInstance = new Singleton();}private Singleton() {// Exists only to default instantiation.}public static Singleton getInstance() {return SingletonHolder.uniqueInstance;}// Other methods...}
For the third implementation benefit, please refer to the English note above. I would like to learn from the master!
4. Singleton mode serialization
/ Serialzable Singleton - Page 11import java.io.*;public class Elvis { public static final Elvis INSTANCE = new Elvis(); private Elvis() { // ... } // ... // Remainder omitted // readResolve method to preserve singleton property private Object readResolve() throws ObjectStreamException { /* * Return the one true Elvis and let the garbage collector * take care of the Elvis impersonator. */ return INSTANCE; } public static void main(String[] args) { System.out.println(Elvis.INSTANCE); }}
You can continue to read this book for more explanations.