单例模式实现方式
2016-10-09 10:51
169 查看
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
相关文章推荐
- [设计模式]DAO的实现方式探讨_Part I
- 黑板模式的常见实现方式
- 单例模式的5种实现方式
- Windows Phone 7 MVVM模式通讯方式之实现Binding Data
- Windows Phone 7 MVVM模式通讯方式之实现Binding Data
- 单态设计模式在 PHP5 中的实现方式
- Windows Phone 7 MVVM模式通讯方式之实现Attached Behavior
- B/S 模式 套打 的一种实现方式<转>
- Singleton_模式_关于单例(Singleton)模式实现方式的反思
- Windows Phone 7 MVVM模式通讯方式之实现Command
- 单例模式的两种实现方式及区别
- 1.singleton模式的的两种实现方式
- B/S 模式 套打 的一种实现方式
- Singleton模式的double check实现方式
- 史上最强jquery1.3.2轻松打造div模式层! asp.net和html和MagicAjax实现3种方式! 已更新!
- [设计模式]DAO的实现方式探讨_Part II
- 【工作流】PE中的资源模式的实现方式
- 设计模式-PHP实现单件模式的几种方式
- 客户端在线方式的实现模式
- Windows Phone 7 MVVM模式通讯方式之实现Command