java的单例设计模式(对象的延时加载)考试专用

java的单例设计模式(对象的延时加载) ,称为:懒汉式    考试专用
例:
package day6;

public class Single2 {  //考试专用  ,对象的延时加载 ,外号:赖汉式
    
    private static Single2 s=null;
    
    private Single2(){        
    }
    
    public static synchronized Single2 getInstance(){  //synchronized同步锁
        if(s==null){  
            s=new Single2();
        }
        return s;
    }
    
    //如果静态函数如上面那样写,效率会很低,
    //解决方案如下(只改变函数,其它的不变)
    public static Single2 getInstance8(){
        if(s==null){
            synchronized(Single2.class){
                if(s==null){
                    s=new Single2();
                }
            }
        }
        return s;
    }
}

原文地址:https://www.cnblogs.com/taobd/p/7044117.html