1. 模式结构
2. 饿汉式单例
类加载的时候就已经创建了单例对象
public class EagerSingleton {
private final static EagerSingleton instance = new EagerSingleton();
private EagerSingleton(){}
public static EagerSingleton getInstance() {
return instance;
}
}
3. 懒汉式单例
第一次引用的时候将自己实例化,实例化时用synchronized以处理多线程环境
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton(){}
synchronized public static LazySingleton getInstance(){
if (instance==null)
instance = new LazySingleton();
return instance;
}
}
4. 应用
Spring框架中的bean工厂默认以单例模式创建bean