面试常考——【懒汉模式】与【饿汉模式】

饿汉模式:

class Singleton {

    private Singleton() {}

    private static Singleton singleton = new Singleton();

    public static Singleton getInstance() {
        return singleton;
    }
}

 

懒汉模式:

public class Singleton {

    private Singleton() {}

    private static Singleton singleton = null;

    public static Singleton getInstance() {
        if (singleton == null) {
            synchronized (Singleton.class) { // 以当前类的字节码对象为锁
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

 

posted @ 2016-11-08 00:09  达哥的博客  阅读(567)  评论(0编辑  收藏  举报