第0章:简介
单例模式定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
单例模式本质:控制实例数目。
参考:http://chjavach.iteye.com/blog/721076 ,研磨设计模式(书籍),大话设计模式(书籍)
模式图:
待补充
第1章:实践
第0节:懒汉式单例模式(非线程安全,延迟加载)
package com.mcc.core.designPattern.build.singleton; /** //全局静态实例 /** } /** public static LazySingleton getInstance(){ |
第1节:饿汉式单例模式(线程安全,预加载)
package com.mcc.core.designPattern.build.singleton; /** * 饿汉式单例模式,线程安全,类装载的时候就会被加载 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-8 下午11:31 */ public class HungrySingleton { //只有一个实例 private static HungrySingleton instance = new HungrySingleton(); /** * 私有构造器控制实例数量 */ private HungrySingleton(){ } /** * 获取实例 * @return */ public static HungrySingleton getInstance(){ return instance; } } |
第2节:volatile关键字实现单例模式(线程安全,延迟加载)
package com.mcc.core.designPattern.build.singleton; /** * volatile关键字实现单例模式,线程安全,延迟加载 * * valatile关键字会屏蔽虚拟机中的一些必要的优化,影响运行效率,非特殊要求一般不用。 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-8 下午11:40 */ public class VolatileSingleton { //volatile关键字修饰,不会被本地线程缓存,多个线程能正确的处理该变量 private volatile static VolatileSingleton instance = null; /** * 私有构造器控制实现数量 */ private VolatileSingleton(){ } public static VolatileSingleton getInstance(){ if (instance == null){ //同步块,线程安全 synchronized (VolatileSingleton.class){ if (instance == null){ instance = new VolatileSingleton(); } } } return instance; } } |
第3节:类级内部类实现单例模式(线程安全,延迟加载)
package com.mcc.core.designPattern.build.singleton; /** * 类级内部类单例模式,线程安全,延迟加载,推荐使用 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-8 下午11:54 */ public class InnerclassSingleton { private static class SingletonHolder{ //静态初始化,由JVM来保证线程安全 private static InnerclassSingleton instance = new InnerclassSingleton(); } /** * 私有构造器控制实例数量 */ private InnerclassSingleton(){ } /** * 全局访问点 * @return */ public static InnerclassSingleton getInstance(){ return SingletonHolder.instance; } } |