Definition:
Ensure that a class has only one instance and that it instantiates itself and makes that instance available to the entire system.Copy the code
Usage Scenarios:
Ensure scenarios where a class has only one object and avoid creating multiple objects that consume too many resources, or where there should be only one object of a certain type.Copy the code
Key points:
  • Constructors are not open to the public and are generally Private.
  • Returns a singleton class object through a static method or enumeration.
  • Ensure that there is one and only one object for a singleton class, especially in a multithreaded environment.
  • Ensure that singleton class objects are not rebuilt when deserialized.
Implementation method:
1. Slacker mode:
* Definition: Lazy mode is to declare a static object and initialize it the first time a user calls an individual Instance. * Code implementation:Copy the code
Public class SingleCode {private static SingleCode instance; private SingleCode(){} public static synchronized SingleCode getInstance(){ if(instance == null ) { instance = new SingleCode(); } return instance; }}Copy the code
Advantages: Singletons are instantiated only when they are used, saving resources to some extent. * Disadvantages: the first load needs to be instantiated, which is slightly slow. The biggest problem is that every time getInstance is called, synchronization is carried out, causing unnecessary synchronization overhead.Copy the code
Double CheckLock(DCL)
* Definition: The advantage of DCL method to implement singleton pattern is that it can not only initialize singleton when needed, but also ensure thread safety, and the singleton object after initialization call getInstance without synchronization lock; * Code implementation:Copy the code
Public class SingleCode {private static SingleCode instance = null; private static Object obj = new Object(); Private SingleCode(){} public static SingleCode getInstance(){if(instance == null) {// Check whether the SingleCode is null to avoid unnecessary synchronized (obj) {if(instance == null) {// In order to create an instance with null instance = new SingleCode(); } } } return instance; }}Copy the code
* Advantages: High resource utilization. The singleton is instantiated only when getInstance is executed for the first time. * Cons: slightly slower to load the first time, and occasionally fails due to the Java memory model.Copy the code
3. Static inner class singleton pattern:
* Code implementation:Copy the code
Private SingleCode(){} public static SingleCode getInstance(){return private SingleCode getInstance(){} public static SingleCode getInstance(){return SingleHolder.instance; Private static final SingleCode instance = new SingleCode(); private static final SingleCode instance = new SingleCode(); }}Copy the code
* Advantages: The first call to getInstance causes the virtual machine to load the SingleHolder class. This method not only ensures thread-safety, but also ensures the uniqueness of the singleton, while delaying the instantiation of the singleton. * The recommended singleton implementation.Copy the code
4. Enumerating singletons:
* Code implementation:Copy the code
public enum SingleEnum{ INSTANCE; public void doSomething(){ System.out.put("do sth."); }}Copy the code
Advantages: Simple to write, the creation of an enumeration instance is thread-safe, and in any case it is a singleton.Copy the code
5. Use containers to implement the singleton pattern:
* Code implementation:Copy the code
        public class SingleManager {
            private static Map<String,Object> objMap = new HashMap<String, Object>();
            private SingleManager(){}
            public static void registerService(String key,Object instance){
                if(!objMap.containsKey(key)) {
                    objMap.put(key, instance);
                }
            }
            public static Object getService(String key) {
                return objMap.get(key);
            }

        }

       
Copy the code
* Advantages container singleton mode can manage a variety of types of singleton, and can be used through a unified interface to obtain the operation, reduce the user use cost, there are hidden to the user the specific implementation, reduce the coupling degree.Copy the code
conclusion
  1. Advantages:
    • Since the singleton pattern has only an occasional instance in memory, it reduces memory overhead, especially when an object needs to be created and destroyed frequently and performance cannot be optimized.
    • Because the singleton pattern generates only one instance, it reduces the performance overhead of the system.
    • The singleton pattern avoids multiple resources.
    • The singleton pattern allows you to set up global access points in the system to optimize and share resource access.
  2. Disadvantages:
    • The singleton pattern generally has no interface and is difficult to extend, and there is almost no other way to extend it than by modifying the code.
    • If a singleton holds a Context, it is likely to cause memory leaks. In this case, you need to note that the Context passed to the singleton is preferably an Application Context.