单例模式

懒汉模式


public class LazyModeSingleton {

private static LazyModeSingletoninstance;

private LazyModeSingleton(){}

public static LazyModeSingletongetInstance(){

if(instance==null) {

instance=new LazyModeSingleton();

}

return instance;

}

}

线程安全的懒汉模式


public class LazySafeModeSingleton {

private static LazySafeModeSingletoninstance;

private LazySafeModeSingleton(){};

public synchronized LazySafeModeSingletongetInstance(){

if(instance==null) {

instance=new LazySafeModeSingleton();

}

return instance;

}

}

双重检查锁


public class DoubleCheckSingleton {

private static DoubleCheckSingletoninstance;

private DoubleCheckSingleton(){}

public static DoubleCheckSingletongetInstance(){

if(instance==null) {

synchronized(DoubleCheckSingleton.class) {

if(instance==null) {

instance=new DoubleCheckSingleton();

}

}

}

return instance;

}

}

源引http://wuchong.me/blog/2014/08/28/how-to-correctly-write-singleton-pattern/

posted on 2018-01-02 13:54  simple_huang  阅读(133)  评论(0编辑  收藏  举报