设计模式之单例模式
来源:互联网 发布:飞利浦x830软件 编辑:程序博客网 时间:2024/06/07 01:03
单例模式
定义是在相关的场景中不能实例化多个对象,比如唯一的标识号码生成器,打印机工作.
看书查阅资料都说单例模式是最简单的,但是对于对线程了解不深的,感觉会很容易考虑缺失很多的问题.
实现单例模式的方式
懒汉式
package com.single.pattern;public class SinglePattern { //延迟加载,加快响应 private static SinglePattern instance = null; //私有化构造函数 private SinglePattern() { } //简单实例化相关类 public static SinglePattern getInstance() { if (instance == null) { instance = new SinglePattern(); } return instance; }}饿汉型(线程不安全)
public class SinglePattern { private static SinglePattern instance = new SinglePattern (); private SinglePattern (){} public static SinglePattern getInstance() { if (instance == null) { instance = new SinglePattern(); } return instance; } }
饿汉型(线程安全)
public class SinglePattern { private static SinglePattern instance = new SinglePattern (); private SinglePattern (){} public static synchronized SinglePattern getInstance() { if (instance == null) { instance = new SinglePattern(); } return instance; } }
静态类型
package com.single.pattern;public class SinglePattern { private SinglePattern() { } //static只能用来修饰内部类或者是变量 //构造私有静态变量 private static class SinglePatternFactory{ private static SinglePattern instance = new SinglePattern(); } public static SinglePattern getInstance(){ return SinglePatternFactory.instance; } //保证序列化 public Object readResolve() { return getInstance(); } public void printInfo(){ System.out.println("生成相关号码"); }}
在懒汉型的实现过程中可以用synchronized实现相关隔离的方式,但会存在对象在函数中是否真正的实例化了问题,如果没有实例化会出现错误.
双重锁型
//volatile的作用是: 作为指令关键字,确保本条指令不会因编译器的优化而省略,且要求每次直接读值.<span style="display: none; width: 0px; height: 0px;" id="transmark"></span>private volatile static SinglePattern singlePattern;private SinglePattern (){}public static SinglePattern getSingleton() { if (singlePattern == null) { synchronized (SinglePattern.class) { if (singlePattern == null) { singlePattern = new SinglePattern(); } } } return singlePattern;}
1 0
- 设计模式之 单例设计模式
- 设计模式之 单例设计模式
- 设计模式之单例设计模式
- 设计模式之-----------单例设计模式
- 设计模式之:单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之-单例设计模式
- 设计模式之单例设计模式 标签: 设计模式
- 设计模式之单例
- 设计模式之单例
- 设计模式之 单例
- iOS中倒计时实现效果
- 使用Button特效 selector+shape
- 安卓通知栏管理详解及分析 NotificationListenerService
- mysql数据库优化
- 几种排序算法总结:
- 设计模式之单例模式
- NYOJ660逃离地球——只为最大存活率~
- Activity活动(上)
- 并查集-poj-1988-Cube Stacking
- A. Far Relative’s Birthday Cake【排列组合】
- Fully Convolutional Networks for Semantic Segmentation
- apache2.2与2.4中的访问控制语句比较
- SDUSTOJ Problem B: 平面上的点——Point类 (II)
- Activity活动(中)