代码改变世界

23种设计模式中的单例模式

2017-08-05 15:12  猪牙哥  阅读(164)  评论(0编辑  收藏  举报

单例模式:确保一个类最多只有一个实例,并提供一个全局访问点。

单例模式在多线程里面的优化:

①同步(synchronized) getInstance方法,缺点:耗资源多,优点:目的达到了

public class XXX {
    
     private static XXX instance;
     
     private XXX(){
         super();
     }
     
     public synchronized static XXX getInstance(){
         if(instance==null){
             instance=new XXX();
         }
         return instance;
     }
    
}

②“急切”创建实例

public class XXX {
    
     private static XXX instance = new XXX();
     
     private XXX(){
         super();
     }
     
     public synchronized static XXX getInstance(){
         return instance;
     }
    
}

③双重检查加锁

public class XXX {

    private volatile static XXX instance;

    private XXX() {
        super();
    }

    public static XXX getInstance() {
        if (instance == null) {
            synchronized (XXX.class) {
                instance = new XXX();
            }
        }
        return instance;
    }

}