java设计模式基础-单例模式的几种写法
来源:互联网 发布:农产品网络推广方案 编辑:程序博客网 时间:2024/06/04 18:35
第一种(线程不安全,多线程不能正常工作):
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
第二种(线程安全,效率很低,99%情况下不需要同步):
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
第三种(静态内部类、延迟初始化方法 推荐使用):
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
注释:这种方式同样利用了classloder的机制来保证初始化instance时只有一个线程
第四种(双重校验锁):
public class Singleton {
2 private volatile static Singleton singleton;
3 private Singleton (){}
4 public static Singleton getSingleton() {
5 if (singleton == null) {
6 synchronized (Singleton.class) {
7 if (singleton == null) {
8 singleton = new Singleton();
9 }
10 }
11 }
12 return singleton;
13 }
14 }
第五种(枚举):
public enum Singleton {
2 INSTANCE;
3 public void whateverMethod() {
4 }
5 }
注释:这种方式是Effective Java作者Josh Bloch 提倡的方式,它不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象,可谓是很坚强的壁垒啊,不过,个人认为由于1.5中才加入enum特性,用这种方式写不免让人感觉生疏,在实际工作中,我也很少看见有人这么写过。
- java设计模式基础-单例模式的几种写法
- Java单例设计模式的几种写法
- 设计模式之单例模式的几种写法
- 【设计模式】 单例模式的几种写法
- Java设计模式之单例模式的几种写法
- Java单例模式几种写法
- Java单例模式的几种写法
- Java单例模式的几种写法详解
- java的单例模式几种写法
- Java:单例模式的几种写法
- Java单例模式的几种写法
- java单例模式的几种写法
- Java单例模式的几种写法
- Java单例模式的几种写法
- java面试(1)单例模式的几种写法
- 单例模式的几种写法
- 单例模式的几种写法
- 单例模式的几种写法
- RFID系统信号的通信过程
- 排序算法性能及选择总结
- Hibernate初始化时的Could not parse configuration
- Building 'MyApplication' Gradle project info 的解决办法 android studio V8.0版本
- 数字三角形问题 NOJ 1226
- java设计模式基础-单例模式的几种写法
- 计算机组成第五周:单周期处理器
- [LeetCode][Database]Nth Hightest Salary
- fgbfdcbfbvcbcvbvcbcvbvc
- String和Date之间的转换。。
- Rainy season best wbp brown film faced plywood
- SecureCRT delete删除出错
- 利用mat遍历图像的方法
- 读书笔记