单例模式实现方式
来源:互联网 发布:网络招聘注意事项 编辑:程序博客网 时间:2024/05/02 00:29
public class Singleton { private Singleton() {} // Lazy initialization holder class idiom for static fields private static class InstanceHolder { private static final Singleton instance = new Singleton(); } public static Singleton getSingleton() { return InstanceHolder.instance; }}
public class LazySingleton { private int someField; private static LazySingleton instance; private LazySingleton() { this.someField = new Random().nextInt(200)+1; // (1) } public static LazySingleton getInstance() { if (instance == null) { // (2) synchronized(LazySingleton.class) { // (3) if (instance == null) { // (4) instance = new LazySingleton(); // (5) } } } return instance; // (6) } public int getSomeField() { return this.someField; // (7) } }
上面这种方式完美,下面这种方式极小可能会出现happen—before问题,导致调用getSomeField()方法返回0
0 0
- 单例模式实现方式
- 最佳单例模式实现方式-单枚举类实现
- 单例模式的多种实现方式
- 单例模式 及其实现方式
- 单例模式两种实现方式
- C++单例模式实现方式
- 四中方式实现单例模式
- 单例模式的多种实现方式
- 不同平台单例模式实现方式
- 单例模式几种实现方式
- 单例模式5种实现方式
- 单例模式的实现方式
- java单例模式的实现方式
- 单例设计模式实现方式
- 单例模式--各种实现方式详解
- Python单例模式的实现方式
- 10001:Chromium单例模式实现方式
- java单例模式的实现方式
- EditText设置监听,实现判断输入了多少个字符。
- java回调与异步网络请求的封装
- 第7周 项目2建立链队算法库
- 程序员技术练级攻略
- 第四周项目5 多项式求和
- 单例模式实现方式
- 笔记整理之--final & static
- 使用StatsD, Graphite, Grafana, Kamon搭建可用于JVM项目的可视化性能监控系统
- Intel Code Challenge Final Round (Div. 1 + Div. 2, Combined) D. Dense Subsequence
- js去掉空格
- API压力测试解决办法
- eclipse+CDT 实现在eclipse中的C++编程
- iOS各种小理论知识
- make modules