单例模式
来源:互联网 发布:fgo阿尔托利亚技能数据 编辑:程序博客网 时间:2024/05/16 04:25
1.对于性能要求不高,可以这样写
public class Singleton_1 { private static Singleton_1 uniqueInstance; //其他变量 private Singleton_1(){} public static synchronized Singleton_1 getInstance(){ if (uniqueInstance == null){ uniqueInstance = new Singleton_1(); } return uniqueInstance; } //其他方法}
2.静态初始化的方式,非动态实例化;适于创建和运行时负担不是太重,eagerly创建单例
public class Singleton_2 { private static Singleton_2 uniqueInstance = new Singleton_2(); //其他变量 private Singleton_2(){} public static synchronized Singleton_2 getInstance(){ return uniqueInstance; } //其他方法}
3.双重检验加锁,从而减少使用synchronized(只有一次),提高性能
public class Singleton_3 { private volatile static Singleton_3 uniqueInstance;//volatile关键字保证读取过程变量的值保持不变 //其他变量 private Singleton_3(){} public static synchronized Singleton_3 getInstance(){ if (uniqueInstance == null){ synchronized (Singleton_3.class){ if (uniqueInstance == null){ uniqueInstance = new Singleton_3(); } } } return uniqueInstance; } //其他方法}
更多:如何正确地写出单例模式http://www.importnew.com/21141.html
0 0
- 单例、单例模式
- 单例模式-多线程单例模式
- 单件模式(单例模式)
- 设计模式------单例模式
- 设计模式------单例模式
- 设计模式-单例模式
- 设计模式 - 单例模式
- 设计模式---单例模式
- 设计模式---单例模式
- PHP模式-单例模式
- 【设计模式】单例模式
- 设计模式-单例模式
- 设计模式----单例模式
- 设计模式--单例模式
- 设计模式-单例模式
- 单例模式(单子模式)
- 设计模式-单例模式
- [设计模式] 单例模式
- MySQL学习5
- mac关于java .bash_profile环境变量配置的问题
- asp.net mvc5 使用百度ueditor 本编辑器完整示例(上)
- JSONObject与JSONArray的使用
- 新闻中文本地域信息标签的抽取
- 单例模式
- 重装电脑遇到的问题(二)
- 【数组3】连续子数组的最大和
- 二分图的判定
- Android使用Fragment搭建界面框架(一)
- 389. Find the Difference [easy] (Python)
- Android 回退键的实现
- Mongodb使用总结
- 年终总结