单例模式
懒汉模式
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/