标签搜索

单例模式

Pop.Kite
2022-01-08 / 0 评论 / 147 阅读 / 正在检测是否收录...
单例模式避免了资源的多次读写导致的同步、性能问题。

饿汉

先生成,用的时候直接引用
//A
public class SingletonInstance {
    private static final SingletonInstance instance= new SingletonInstance();

    public SingletonInstance getInstance(){
        return instance;
    }
}
//B 
public class SingletonInstance {
    private static final SingletonInstance instance;

    static {
        instance = new SingletonInstance();
    }

    public SingletonInstance getInstance() {
        return instance;
    }
}
//C
public class SingletonInstance {
    private static class SingletonHolder {
        private static final SingletonInstance instance = new SingletonInstance();
    }

    public SingletonInstance getInstance() {
        return SingletonHolder.instance;
    }
}

懒汉 - 双重校验锁

用的时候再生成
public class SingletonInstance {
    private static volatile SingletonInstance instance;

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

枚举

枚举类的成员默认是Static Final
public enum SingletonInstance {
    getInstance()
}
0

评论 (0)

取消