单例模式:类保证只有一个实例存在。
分为:懒汉模式和饿汉模式。
懒汉模式:类加载时不进行实例化。
/**
* 懒汉模式:加载时不初始化
* @author lenovo
*
*/
public class LazySingleton {
private static LazySingleton instance = null;
private LazySingleton () {
}
public static synchronized LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
饿汉模式:加载类时进行实例化
/**
* 饿汉模式:加载类时就初始化
* @author lenovo
*
*/
public class EagerSinglton {
private static EagerSinglton instance = new EagerSinglton();
private EagerSinglton () {
}
public static EagerSinglton getInstance () {
return instance;
}
}