Detailed explanation of the singleton model

Posted by sholah on Sat, 22 Jun 2019 02:40:45 +0200

 Singleton Design Patterns

Singleton is a kind of creation mode, which means that a class uses Singleton mode. After the class is created, only one instance can be generated for external access and a global access point can be provided.

The core knowledge points are as follows:

(1) The construction method of the class using the singleton design pattern will be privatized (with private modification).

(2) Instance objects of this class are generated inside it and encapsulated as private static types.

(3) Define a static method to return an instance of the class.

Hungry Chinese Style
The advantages are: it is simple to write, and there is no multi-threaded synchronization problem, avoiding the performance problems caused by synchronized;
The disadvantage is that when the class Singleton is loaded, the instance of static is initialized, the static variable is created and allocated memory space. Since then, the instance object of static occupies the memory (even if you haven't used the instance yet). When the class is unloaded, the static variable is destroyed and the memory occupied is released, so under certain conditions. It consumes memory.

/** 
 * The implementation of singleton mode: hungry Chinese, thread-safe, but inefficient 
 */  public class Singleton {  

    // Define a private construction method    
    private Singleton() {  
    }  

    // Set your own instance object as an attribute with Static and final modifiers    
    private static final Singleton instance = new Singleton();  

    // Static methods return instances of this class    
    public static Singleton getInstancei() {  
        return instance;  
    }  
  
}

Lazy-man Style

The advantage is that it is relatively simple to write. When the class Singleton is loaded, instance of static variable is not created and memory space is allocated. When the getInstance method is first called, instance variable is initialized and memory is allocated, so memory is saved under some specific conditions.
The disadvantage is that multiple Singleton instances are likely to occur in a concurrent environment, which is non-thread-safe.

/**  
 * Realization of Singleton Mode: Lazy Non-Thread Security   
 *   
 */  public class Singleton {

    // Define a private constructor (to prevent de-instantiation through new Singleton()    
    private Singleton() {   
    }   

    // Define a variable of type Singleton (not initialized, note that the final keyword is not used here)  
    private static Singleton instance;   

    // Define a static method (Singleton Test is initialized when invoked, but repeated initialization may occur when multithreaded access is made)   
    public static Singleton getInstance() {   
      if (instance == null)   
       instance = new Singleton();   
      return instance;   
    }   
}

Lazy Man Optimize I
The advantage is that when synchronized keywords are used to avoid multithreaded access, multiple Singleton instances appear.
The disadvantage is that the efficiency of synchronization method is slightly low when it is frequently called.

/**  
 * Realization of singleton mode: lazy, simple implementation of thread security   
 *   
 */  public class Singleton {

    // Define a private constructor (to prevent de-instantiation through new Singleton()
    private Singleton() {   
    }   

    // Define a variable of type Singleton (not initialized, note that the final keyword is not used here)
    private static Singleton instance;   

    // Define a static method (Singleton is reinitialized when invoked, and multiple reinitialization problems may occur when synchronized is used to avoid multithreaded access)
    public static synchronized  Singleton getInstance() {   
        if (instance == null)   
          instance = new Singleton();   
        return instance;   
    }   
}

Lazy man optimization II

The best implementation of the singleton pattern. Memory occupancy, high efficiency, thread safety, multi-threaded operation atomicity.

/**  
 * Lazy-man Optimal Scheme of Single-case Model
 * Threads are safe and efficient  
 *   */  
 public class Singleton { 

    // Define a private constructor   
    private Singleton() { 
     
    }   
    //Define a static private variable (no initialization, no final keyword, volatile guarantees multithreaded access)
    //The visibility of instance variable avoids being invoked by another thread when other variable attributes have not been assigned at instance initialization.    
    private static volatile Singleton instance;  

    //Define a common static method that returns an instance of that type    
    public static Singleton getIstance() { 
     //Whether or not to judge the instantiation of objects (instance equals null, do not enter the synchronous code block, return the objects directly, improve the efficiency of operation)        
     if (instance == null) {
       //Synchronized code blocks (when objects are not initialized, synchronized code blocks are used to ensure that objects are not created again after the first creation of multithreaded access)            
        synchronized (Singleton.class) {
      //Initialized, the initial instance variable                
       if (instance == null) {
       instance = new Singleton();   
       }   
       }   
      }   
     return instance;   
    }   
}

Registration Form

Internal classes are loaded only when external classes are called, generating Singleton instances without locking. This mode has the advantages of the two modes mentioned above, shielding their shortcomings, and is the best single-case mode.

public class Singleton{  
 // Define a private constructor     
 private Singleton(){}  
 
 public static Singleton getInstance(){ 
    return Holder.singleton;
 }   
 //Internal class
 private static class Holder{
    private static final Singleton singleton= new Singleton();
 }
}


Reference resources: http://www.cnblogs.com/yinxiaoqiexuxing/p/5605338.html

Topics: Java Attribute