设计模式之单件模式(Singleton)
来源:互联网 发布:江苏远洋数据有限公司 编辑:程序博客网 时间:2024/06/05 18:49
单件模式或者叫单例模式,表示类只能创建一个实例对象。
用途也比较广泛,比如线程池(Threadpool)、缓存(cache)、对话框、处理偏好设置和注册表的对象、日志对象,充当打印机、显卡等设备的驱动程序的对象,都只需要一个实例。如果制造多个实例对象,就可能会产生很多问题。
单件模式的经典实现:
public class Singleton { private static Singleton uniqueInstance; private Singleton() { } public static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; }}
上面的经典实现虽然实现了其功能,但是只局限于单线程,在多线程环境下,可能会出错。
下面几种方式是解决多线程安全的单例模式实现。
1. 通过synchronized 关键字实现
public class Singleton { private static Singleton uniqueInstance; private Singleton() { } public static synchronized Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; }}
2. 通过急切实例化方法实现
public class Singleton { private static Singleton uniqueInstance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return uniqueInstance; }}
3. 通过“双重检查加锁”实现
public class Singleton { private static volatile Singleton uniqueInstance; private Singleton() { } public static Singleton getInstance() { if (uniqueInstance == null) { synchronized(Singleton.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } } } return uniqueInstance; }}
第三种方法比第一种方法有点在于只有第一次执行时synchronized可能会阻塞多线程的运行,以后都不会再进入synchronized块。其中volatile的作用是保证变量的修改和读取都是直接从内存中写入和读取的,不会出现多线程导致变量读取不同的情况。
0 0
- 设计模式之Singleton(单件模式)
- 设计模式之单件模式 singleton
- 设计模式之单件模式(Singleton)
- 设计模式之Singleton(单件)
- C++设计模式之Singleton(单件/单例)模式
- Singleton (单件) 设计模式
- Singleton单件设计模式
- 设计模式之单件模式(Singleton)
- 设计模式之单件模式(Singleton Pattern )
- VB.net设计模式之单件模式(singleton)
- C#设计模式之单件模式(Singleton Pattern)
- 魔兽争霸之PHP设计模式-单件模式[Singleton]
- 设计模式学习之单件模式singleton
- 设计模式之——单件模式(Singleton)
- 设计模式之单件模式(Singleton Pattern)
- C++设计模式之五:SINGLETON(单件模式)
- java设计模式之单件模式Singleton
- android设计模式--之单件模式(singleton)
- 2016-03-03 道 法 儒
- Volley错误可能情况
- Spring读取配置文件的几种方式及依赖
- LASlib编译和配置LASlib (VS2013 release win7 64位)
- Leetcode Number of Digit One
- 设计模式之单件模式(Singleton)
- MySQL之设置数据库之间主主同步---主主同步,相互备份
- java中数据存储问题
- STL算法之排序
- 创建maven web工程
- Android技术积累:开发规范
- kafka监控Kafka Offset Monitor
- Missing Number
- 初接触jquery easyui的一点认知