前言
大致的了解了一下单例模式的实现,经供参考!
常见实现(懒汉和饿汉)
懒汉式单例模式
/**
* 懒汉式,先不创建实例,等到需要时在创建。
* 多线程情况下并发效率低。
* 结论:线程安全,调用效率不高,但是可以延时加载。
*/
public class LazySingleton {
/**
* 静态实例变量
*/
private static LazySingleton instance;
/**
* 私有构造函数
*/
private LazySingleton() {
}
/**
*懒汉式创建实例,需要同步处理
* @return
*/
public static synchronized LazySingleton getInstance(){
if (instance == null){
instance = new LazySingleton();
}
return instance;
}