单例模式

确保任何情况下都只有一个实例

饿汉式

public class Singleton {
//在类被加载的时候运行一次,这是本类构造函数的唯一一次使用。
//未被使用之前就已经实例化完成,称为饿汉式
private static Singleton singleton = new Singleton(); //构造函数为私有的,只有本类才能构造实例
private Singleton() {
System.out.println("生成了一个Singleton实例");
} //外界只能通过唯一的getInstance方法获得这个唯一的实例
public static Singleton getInstance() {
return singleton;
}
}

优点:实现简单,没有线程同步问题。

缺点:实例会一直占用内存,浪费空间。

懒汉式

public class Singleton2 {
private static Singleton2 instance; private Singleton2() {} public static Singleton2 getInstance() {
//在别人需要的时候才开始实例化
if(instance == null) {
instance = new Singleton2();
}
return instance;
}
}

优点:实例化推迟到需要之时,不浪费内存空间。

缺点:线程不安全

线程安全的懒汉式

public class Singleton3 {
private static Singleton3 instance; private Singleton3() {} public static Singleton3 getInstance() {
if(instance == null) {
//需要时创建,并且只对关键代码块加锁,保证性能
synchronized (Singleton3.class) {
if (instance == null) {
instance = new Singleton3();
}
}
}
return instance;
}
}

优点:推迟加载,占用空间少,线程安全

缺点:麻烦

最新文章

  1. HTTP 基础知识
  2. C语言-自定义函数
  3. iOS NSUserDefaults 存放位置
  4. 转载: Asp.net常见word,excel,ppt,pdf在线预览方案
  5. synchronized 关键字
  6. Dreamweaver中打开CodeSmith文件
  7. SQLServer性能优化
  8. IDEA开发工具的学习
  9. 其他shell
  10. supervisor简要使用说明
  11. js-DOM事件
  12. 十万的License只取决于一个连接
  13. Unity3D工程全资源自动检测系统
  14. html 居中的内容显示框
  15. mysqlbinlog基于某个偏移量进行数据的恢复(重做),--start-position,--stop-position的使用方法
  16. Android 引用资源
  17. 不修改代码优化 ASP.NET 网站性能的一些方法
  18. NSArray与NSMutableArray 数组与可变数组的创建和遍历 复习
  19. vertical-align和line-height的深入应用
  20. 第25章 串行FLASH文件系统FatFs

热门文章

  1. 中国剩余定理(CRT) & 扩展中国剩余定理(ExCRT)总结
  2. CentOS 5.5编译安装lnmp
  3. 十二、支持向量机(Support Vector Machines)
  4. python里的排序
  5. HDU-1873 看病要排队(队列模拟)
  6. P3452 [POI2007]BIU-Offices
  7. Python之路-Python中文件和异常
  8. 百度地图api 实例 自动提示 并计算两地的行驶距离
  9. python之流程控制升级
  10. linux 服务器与客户端异常断开连接问题