How to implement a single case
1. The constructor needs to be privatized
2. Provide a private static variable
3. Expose a common interface to obtain singleton objects
Two issues to consider
1. Whether lazy loading is supported
2. Is it thread safe?
1. Hungry Man Style
public class EagerSingleton { private static final EagerSingleton INSTANCE = new EagerSingleton(); private EagerSingleton(){} public EagerSingleton getInstance(){ return INSTANCE; } }
Lazy loading is not supported
Thread safety
2. Lazy style
public class LazySingleton { private static LazySingleton INSTANCE; private LazySingleton() { } public static LazySingleton getInstance() { if (INSTANCE == null) { INSTANCE = new LazySingleton(); } return INSTANCE; } }
Support lazy loading
Threads are not safe
public class LazySingleton { private static LazySingleton INSTANCE; private LazySingleton() { } public static synchronized LazySingleton getInstance() { if (INSTANCE == null) { INSTANCE = new LazySingleton(); } return INSTANCE; } }
Support lazy loading
Thread safety
3. Double check lock
public class DoubleCheckSingleton { private static DoubleCheckSingleton INSTANCE; private DoubleCheckSingleton() { } public DoubleCheckSingleton getInstance() { if (INSTANCE == null) { synchronized () { if (INSTANCE == null) { INSTANCE = new DoubleCheckSingleton(); } } } return INSTANCE; } }
Support lazy loading
Thread safety
4. Static internal class
public class InnerSingleton { private InnerSingleton() { } public static InnerSingleton getInstance() { return ; } private static class Singleton { private static final InnerSingleton INSTANCE = new InnerSingleton(); } }
Support lazy loading
Thread safety
5. Enumeration
public enum EnumSingleton { INSTANCE; }
Summarize
This is the end of this article about five ways to implement singleton mode in Java. For more related content on Java implementation singleton mode, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!