饿汉
/**
* 饿汉模式,类加载时就生成一个实例,此后不再生成。
* 优点:不需要考虑多线程模式
* 缺点:提前占用系统资源
* @author dakele123
*
*/
public class EagerSingleInstance {
private static EagerSingleInstance sInstance = new EagerSingleInstance();
private EagerSingleInstance() {
}
public static EagerSingleInstance getInstance() {
return sInstance;
}
}
饱汉
/**
* 饱汉模式/懒汉模式,lazy-loading,第一次调用getInstance时才调用
* lazy-loading
* 需要考虑线程问题
* @author dakele123
*
*/
public class LazySingleInstance {
private static LazySingleInstance sInstance = null;
private LazySingleInstance() {
}
public static LazySingleInstance getInstance() {// 双重验证,保证性能
if (sInstance == null) {
synchronized (LazySingleInstance.class) {// 加同步
if (sInstance == null) {
sInstance = new LazySingleInstance();
}
}
}
return sInstance;
}
}