设计模式之单例模式
2016-05-30 19:22
197 查看
单例模式概要
单例的线程安全性( 懒加载会产生线程安全性)单例加载,是否懒加载(使用时才生成对象)
以下只讨论懒加载
线程安全的解决
线程的不安全性在于singleInstance==null 的判断,如果两个线程同时执行这步,就会产生两个对象,破坏了单例。public class SingleInstance { private static SingleInstance singleInstance; private SingleInstance() { } public static SingleInstance get(){ if(singleInstance==null){ singleInstance=new SingleInstance(); } return singleInstance; } }
低效率锁
public static synchronized SingleInstance get(){ if(singleInstance==null){ singleInstance=new SingleInstance(); } return singleInstance; }
常用的dcl 双检测锁。省略了在mInstance!=null时的同步。
如果希望更安全可以,使用volatile 关键字。
public static SingleInstance get(){ if(singleInstance==null) { synchronized (SingleInstance.class){ if (singleInstance == null) { singleInstance = new SingleInstance(); } } } return singleInstance; }
静态内部类单例模式,第一次加载Singleton 类时不会加载SingleetonHodler 类,第一次调用getInstance 方法会导致虚拟机加载SingletonHolder 类。 虚拟机能够保证线程安全。
public class Singleton { private Singleton(){} public static Singleton getInstance(){ return SingletonHolder.sInstance; } private static class SingletonHolder{ private static final Singleton sInstance =new Singleton(); } }
相关文章推荐
- PropertyChangeListener简单理解
- 什么是设计模式
- 设计模式之创建型模式 - 特别的变量问题
- 七、设计模式——装饰模式
- 设计模式总结
- 设计模式之创建型模式
- 浅谈设计模式的学习
- Ruby设计模式编程之适配器模式实战攻略
- 实例讲解Ruby使用设计模式中的装饰器模式的方法
- 设计模式中的模板方法模式在Ruby中的应用实例两则
- Ruby设计模式编程中对外观模式的应用实例分析
- 实例解析Ruby设计模式编程中Strategy策略模式的使用
- Ruby中使用设计模式中的简单工厂模式和工厂方法模式
- Ruby使用设计模式中的代理模式与装饰模式的代码实例
- 详解组合模式的结构及其在Ruby设计模式编程中的运用
- C#编程中使用设计模式中的原型模式的实例讲解
- 使用设计模式中的工厂方法模式进行C#编程的示例讲解
- 实例解析C#设计模式编程中简单工厂模式的使用
- 详解C#设计模式编程中生成器模式的使用
- 深入解析C#设计模式编程中对建造者模式的运用