《图解设计模式》读书笔记3-1 Singleton模式
2024-08-29 00:10:26
单例模式
确保任何情况下都只有一个实例
饿汉式
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;
}
}
优点:推迟加载,占用空间少,线程安全
缺点:麻烦
最新文章
- HTTP 基础知识
- C语言-自定义函数
- iOS NSUserDefaults 存放位置
- 转载: Asp.net常见word,excel,ppt,pdf在线预览方案
- synchronized 关键字
- Dreamweaver中打开CodeSmith文件
- SQLServer性能优化
- IDEA开发工具的学习
- 其他shell
- supervisor简要使用说明
- js-DOM事件
- 十万的License只取决于一个连接
- Unity3D工程全资源自动检测系统
- html 居中的内容显示框
- mysqlbinlog基于某个偏移量进行数据的恢复(重做),--start-position,--stop-position的使用方法
- Android 引用资源
- 不修改代码优化 ASP.NET 网站性能的一些方法
- NSArray与NSMutableArray 数组与可变数组的创建和遍历 复习
- vertical-align和line-height的深入应用
- 第25章 串行FLASH文件系统FatFs