效率最高的单身人士模式?

时间:2015-08-30 14:38:09

标签: design-patterns singleton

我正在阅读有关单身人士的内容,并且不明白为什么会这样做

public class BillPughSingleton {
    private BillPughSingleton(){}

    private static class SingletonHelper{
        private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }

    public static BillPughSingleton getInstance(){
        return SingletonHelper.INSTANCE;
    }
}

比这个

更有效率
public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
    if(instance == null){
        synchronized (ThreadSafeSingleton.class) {
            if(instance == null){
                instance = new ThreadSafeSingleton();
            }
        }
    }
    return instance;
}

1 个答案:

答案 0 :(得分:1)

第一种模式可以为您节省麻烦和性能,并节省开销。检查null - 类加载器应该确保该类只加载并初始化一次。