设计模式之单例模式
来源:互联网 发布:淘宝模特摆拍技巧 编辑:程序博客网 时间:2024/06/13 23:45
单例模式
单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为
比如:全局信息配置
单例模式最简单的实现:
public class Singleton { private Singleton() { System.out.println("Singleton is create"); } private static Singleton instance = new Singleton(); public static Singleton getInstance() { return instance; }}
由私有构造方法和static来确定唯一性。
缺点:何时产生实例 不好控制
虽然我们知道,在类Singleton第一次被加载的时候,就产生了一个实例。
但是如果这个类中有其他属性
public class Singleton { public static int STATUS=1; private Singleton() { System.out.println("Singleton is create"); } private static Singleton instance = new Singleton(); public static Singleton getInstance() { return instance; }}
当使用
System.out.println(Singleton.STATUS);
这个实例就被产生了。也许此时你并不希望产生这个实例。
如果系统特别在意这个问题,这种单例的实现方法就不太好。
第二种单例模式的解决方式:
public class Singleton { private Singleton() { System.out.println("Singleton is create"); } private static Singleton instance = null; public static synchronized Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; }}
让instance只有在调用getInstance()方式时被创建,并且通过synchronized来确保线程安全。
这样就控制了何时创建实例。
这种方法是延迟加载的典型。
但是有一个问题就是,在高并发的场景下性能会有影响,虽然只有一个判断就return了,但是在并发量很高的情况下,或多或少都会有点影响,因为都要去拿synchronized的锁。
为了高效,有了第三种方式:
public class StaticSingleton { private StaticSingleton(){ System.out.println("StaticSingleton is create"); } private static class SingletonHolder { private static StaticSingleton instance = new StaticSingleton(); } public static StaticSingleton getInstance() { return SingletonHolder.instance; }}
由于加载一个类时,其内部类不会被加载。这样保证了只有调用getInstance()时才会产生实例,控制了生成实例的时间,实现了延迟加载。
并且去掉了synchronized,让性能更优,用static来确保唯一性。
阅读全文
0 0
- 设计模式之 单例设计模式
- 设计模式之 单例设计模式
- 设计模式之单例设计模式
- 设计模式之-----------单例设计模式
- 设计模式之:单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之-单例设计模式
- 设计模式之单例设计模式 标签: 设计模式
- 设计模式之单例
- 设计模式之单例
- 设计模式之 单例
- remove-element
- error C2664: “wsprintfW”: 不能将参数 2 从“const char [6]”转换为“LPCWSTR”;error C2665: “AfxMessageBox”: 2 个重载中
- 学生中遇到的问题(五)
- Python Script文件结构
- OCR调研
- 设计模式之单例模式
- AsyncTask和BackStack,Intent七大属性,运行模式
- RecycleView的通用适配器BaseQuickAdapter处理item中子控件的点击事件以及cardview卡片阴影
- LPTSTR、LPCSTR、LPCTSTR、LPSTR的来源及意义
- TCP时间戳的理解
- JavaScript 对数组进行去重
- 会话跟踪技术
- Spring的一些好处
- Swt活动面板(OLE ActiveX Composite)