4 ways to implement the singleton pattern

Not much to say, there are many examples on the post code online, this is what I typed locally.



package test;


public class Singleton {
    /*
    // Hungry-style singleton mode implements
    private Singleton(){}
    
    private static Singleton instance = new Singleton();

    public static Singleton getInstance(){
        
        return instance;        
    }*/
    
    /*
    / / Lazy singleton implementation When thread AB enters the get method at the same moment, it is firstly empty. After A enters and executes, B executes and is also judged to be empty multiple times. New is not unique. Double judgment is required (double check locking)
    private static Singleton instance = null;
    private Singleton(){}
    public static Singleton getInstance(){
        
        if(instance==null){
        synchronized (Singleton.class) {    
                instance =new Singleton();
            }
        }    
        return instance;
    }*/
    /*// Lazy double check lock
    private volatile static Singleton instance = null;//Do not cache each value refresh
    
    private Singleton(){}
    
    public static Singleton getInstance(){
        
        if(instance== null){
            synchronized(Singleton.class){
                if(instance==null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }*/
    // IoDH implements singleton mode
    private Singleton(){}
    
    private static class HolderClassr{
        private static final Singleton instance =new Singleton();
     }
    
    public static Singleton getInstance(){
        return HolderClassr.instance;
    }
                
    
    public static void main(String[] args){
        
        Singleton s1,s2;
        s1 = Singleton.getInstance();
        s2 = Singleton.getInstance();
        System.out.println(s1==s2);
        
        
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325571310&siteId=291194637