The Java singleton pattern is Shared in four ways

  • 2020-04-01 02:57:21
  • OfStack

1. Java Concurrency In Practice List


public class Singleton {  
    private static class SingletonHolder {  
        public static Singleton resource = new Singleton();  
    }  
    public static Singleton getResource() {  
        return  SingletonHolder.resource ;  
    }  

    private Singleton(){  

    }  
}

2, the effective Java


public class Singleton {  
    public static final Singleton INSTANCE = new Singleton();  

    private Singleton(){}  

    public void method(){  
        //...  
    }  
    public static void main(String[] a){  
        //Call the method.  
        Singleton.INSTANCE.method();  
    }  
}

3, the use of enumeration clever to create a single instance


  
public enum Singleton {  
    INSTANCE;  
    public void method(){  
        //...  
    }  
    public static void main(String[] a){  
        //Call the method.  
        Singleton.INSTANCE.method();  
    }  
} 

4. Double lock


public class Singleton {  
    private static volatile Singleton instance = null;  
      
    private Singleton(){  
        System.out.println("init");  
    }  
    public static  Singleton getInstance(){  
        if(instance == null){  
            synchronized(Singleton.class){  
                if(instance == null){  
                    instance = new Singleton();  
                }  
            }  
        }  
        return instance;  
    }  
} 


Related articles: