几种单例模式

1. 懒汉-线程不安全

public class SingleLon{
    private static SingleLon instance = null;
    private SingleLon(){}
    public  static SingleLon getInstance(){
        if(singleLon == null){
              instance = new SingleLon();
        }
        return instance;
    }

}        

  

2. 懒汉-线程安全

public class SingleLon{
    private static SingleLon instance = null;
    private SingleLon(){}
    public  static Sychronized SingleLon getInstance(){
        if(singleLon == null){
              instance = new SingleLon();
        }
        return instance;
    }

} 

  

3. 饿汉-线程安全-内存占用较大,类加载时就创建了实例

public class SingleLon{
    private static SingleLon instance = new SingleLon();
    private SingleLon(){}
    public  static SingleLon getInstance(){
        return instance;
    }

} 

  

4. 双锁

public class SingleLon{
    private static SingleLon instance = null;
    private SingleLon(){}
    public  static SingleLon getInstance(){
        if(instance == null){
              Sychronized(SingleLon.class){
                   if(instance == null){
                      instance = new SingleLon();
                   }
              }
              
        }
        return instance;
    }

} 

  

原文地址:https://www.cnblogs.com/leavescy/p/12793376.html