一、定义
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
二、实现
//饿汉式
public class EagerSingleton {
private EagerSingleton() { }
private static final EagerSingleton m_instance = new EagerSingleton();
public static EagerSingleton getInstance() {
return m_instance;
}
}
//懒汉式
public class LazySingleton {
private LazySingleton(){}
private static LazySingleton lazySingleton = null;
public static LazySingleton getInstance() {
if (lazySingleton == null) {
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
}