设计模式之单例模式
来源:互联网 发布:现货电子交易软件 编辑:程序博客网 时间:2024/06/06 02:21
基本概念
单例模式指的是:对于某一个类,整个程序中值存在一个该类的实例对象。常见的比如数据库连接对象等。代码示例,单例模式的几种写法及优劣
/** * 饿汉式写法,多线程下不能保证对象的确定性**/public class SingletonHungryUnsec { private static SingletonHungryUnsec instance; private SingletonHungryUnsec() { } /** * 饿汉式,且线程不安全 * @return instancce */ public static SingletonHungryUnsec getInstance (){ if (null == instance) { instance = new SingletonHungryUnsec(); } return instance; }}实际操作时,不推荐这样的写法。
public class SingletonHungrySec { private static SingletonHungrySec instance; private SingletonHungrySec() { } /*** * 饿汉式,线程安全型 * @return instance */ public static SingletonHungrySec getInstance () { if (null == instance) { synchronized (SingletonHungrySec.class) { if (null == instance) { instance = new SingletonHungrySec(); } } } return instance; }}
以上这种写法,通过synchronized关键字,在创建实例对象时,进行双重校验,确保了对象的唯一性。
当然,也可以在方法的定义上加synchrozied关键字,只是多了不必要的同步,每次getInstance()时,都需要加锁解锁操作。
public class SingletonFull { private static final SingletonFull instance = new SingletonFull(); private SingletonFull() { } public static SingletonFull getInstance (){ return instance; }}
上面这样的写法是饱汉式,即在声明属性的时候已经创建了实例对象,后续程序中只需要调用获取即可,但是这种方式并没有达到lazy loader的效果。
0 0
- 设计模式之 单例设计模式
- 设计模式之 单例设计模式
- 设计模式之单例设计模式
- 设计模式之-----------单例设计模式
- 设计模式之:单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之-单例设计模式
- 设计模式之单例设计模式 标签: 设计模式
- 设计模式之单例
- 设计模式之单例
- 设计模式之 单例
- Linux 内存不足
- 蓝桥杯数独游戏——C语言版
- 2016年3月19日:如何让一个单网页自适应手机
- POJ 1753Flip Game
- 三层架构中使用实体类填充泛型集合代替DataTable解决方案(ASP.NET+C#)
- 设计模式之单例模式
- 六大排序算法c++实现
- 宋仲基太阳的后裔头像 撩到你了吗
- React-Native schema跳转
- POJ 2488A Knight's Journey(DFS)
- sql 的一些数据优化
- CentOS 7下autojump无法使用的可能原因
- 自定义排序函数
- 数位DP专题