单例设计模式

来源:互联网 发布:最好的扫描识别软件 编辑:程序博客网 时间:2024/06/08 01:30

单例子设计模式

1、概述

单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。

2、饿汉和懒汉单例设计模式

2、1饿汉单例模式

饿汉单例代码coding

/** * <h3>饿汉单例设计模式</h3><br>* 备注:饿汉单例设计模式不会出现多线程安全问题。* @author @xuyi* @Date @2016年4月5日 @下午10:11:33* @类名 @HungrySingleton* @描述* @春风十里不如你*/public class HungrySingleton {// 标准的写法应该是这样的,使用final 修饰,一声明就初始化对象。private static final HungrySingleton SINGLETON = new HungrySingleton();// 私有化构造方法private HungrySingleton() {}// 获得单例对象的静态方法public static HungrySingleton getInstance() {    return SINGLETON;}}

2、2懒汉单例模式(延迟加载)

懒汉单例代码coding

/*** <h3>懒汉单例设计模式(又称延迟加载设计模式)</h3> <br>* 备注:多线程情况下,如果设计不好会出现线程安全问题。* @author @xuyi* @Date @2016年4月5日 @下午10:00:04* @类名 @LazySingleto* @描述* @春风十里不如你*/public class LazySingleton {// 单例对象声明private volatile static LazySingleton singleton = null;//使用volatile修饰是为了下面双重判断的,保证多线程之间的可见性。// 私有化构造方法private LazySingleton() {}// 获得单例静态方法(单线程情况下,这种写法没有问题多线程就会出现问题了)public static LazySingleton getInstance1() {    if (singleton == null) {        singleton =new LazySingleton();    }         return singleton;}// 获得单例静态方法(多线程也适用)public static LazySingleton getInstance2() {    synchronized (LazySingleton.class) {        if (singleton == null) {            singleton =new LazySingleton();        }             return singleton;    }}// 获得单例静态方法(多线程也适用,并且在并发比较高的时候可以提高性能操作)public static LazySingleton getInstance3() {    if (singleton == null) {        synchronized (LazySingleton.class) {            if (singleton == null) {                singleton = new LazySingleton();            }                 return singleton;        }    } else        return singleton;    // 通过二次判断signleton是否为空来避免每次都判断线程是否持有锁对象。}}

3、应用场景和总结

…待补充


0 0
原创粉丝点击