Java线程安全的单例模式

2018-11-10  本文已影响0人  Seaofdesire

简单的单例模式(饿汉模式)

class SimpleSingleton {

    private static SimpleSingleton ss = new SimpleSingleton();

    private SimpleSingleton() {
    }

    public static SimpleSingleton getInstance() {
        return ss;
    }
}

懒加载的单例模式

class LazySingleton {
    private static LazySingleton ls = null;

    private LazySingleton() {
    }

    public static synchronized LazySingleton getInstance() {
        if (ls == null) {
            ls = new LazySingleton();
        }
        return ls;
    }
}

双锁延迟加载

class DoubleLockSingleton {
    private static DoubleLockSingleton ds = null;

    private DoubleLockSingleton() {

    }

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

内部类实现(推荐)

class InnerSingleton {
    private InnerSingleton() {
    }

    public static InnerSingleton getInstance() {
        return InnerClass.ins;
    }

    private static class InnerClass {
        private static final InnerSingleton ins = new InnerSingleton();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读