单例模式常用方法
来源:互联网 发布:数组和指针 编辑:程序博客网 时间:2024/09/21 09:02
Singleton模式是什么,这里不解释,直接上代码。这里分享了5种写法,并附上了评论。有好有坏,大家自行理解。
/** * 常见面试题:实现单例模式
public class Singleton {
/** * 写法一 <br> * 最直接的初级写法,忽略了对多线程并发的考虑。
* 不推荐 * *
static class SingletonOne {
// 私有化构造函数是必须的 private SingletonOne() { } static SingletonOne instance = null; static SingletonOne getInstance() { if ( instance == null) { instance = new SingletonOne(); } return instance; } }
/** * 写法二 * 考虑到多线程并发的情况,加锁控制。 * 功能正确,但是效率不高,每次获取实例都需要先获取锁。 * 不推荐 */ static class SingletonTwo { // 私有化构造函数是必须的 private SingletonTwo() { } static SingletonTwo instance = null; static synchronized SingletonTwo getInstance() { if ( instance == null) { instance = new SingletonTwo(); } return instance; } } /** * 写法三 <br> * 考虑到多线程并发的情况,加锁控制。 <br> * 同时考虑到效率问题,进行二次判断,只在需要创建新实例的时候加锁。获取的时候无锁 <br> * 勉强过关 */ static class SingletonThree { // 私有化构造函数是必须的 private SingletonThree() { } static SingletonThree instance = null; static byte[] lock = new byte[0]; static SingletonThree getInstance() { if ( instance == null) { synchronized ( lock) { if ( instance == null) { instance = new SingletonThree(); } } } return instance; } } /** * 写法四 <br> * 考虑到多线程并发的情况,利用Java执行原理,静态方法执行一次 <br> * 无锁,效率高 <br> * 缺点:无论使用与否,都预先初始化完成。浪费资源。 <br> * 推荐写法的一种 */ static class SingletonFour { // 私有化构造函数是必须的 private SingletonFour() { } static SingletonFour instance = new SingletonFour(); static SingletonFour getInstance() { return instance; } } /** * 写法四 <br> * 考虑到多线程并发的情况,通过内部类实现按序初始化,且无锁 <br> * 最推荐的写法 */ static class SingletonFive { static class Inner { static SingletonFive new_instance = new SingletonFive(); } // 私有化构造函数是必须的 private SingletonFive() { } static SingletonFive getInstance() { return Inner. new_instance; } }
}
0 0
- 单例模式常用方法
- 单例模式常用方法
- Python创建单例模式的5种常用方法
- 单例模式常用写法
- java 常用设计模式------单例模式
- 常用设计模式之单例模式
- 常用的设计模式----单例模式
- 常用设计模式之单例模式
- 单例模式多种方法
- 单例模式实现方法
- 单例模式实现方法
- 单例模式与工厂方法模式
- Foundation框架第十五弹:自定义单例模式的常用方法
- iOS常用设计模式:单例
- 我常用的 C++ 单例模式
- 常用单例模式:饿汉式&懒汉式
- 几种常用单例模式
- JAVA 三种常用单例模式
- 卫哲:未来中国消费市场的变与不变
- android平台的三个编译命令----make,mm,mmm
- HTTP 之post和get请求
- PCA 和 KLT
- AbstractListView源码分析8
- 单例模式常用方法
- android uiautomator自定义方法输出yyyy-MM-dd HH:mm:ss的时间
- 算法与数据结构:1-5
- iOS 国际化EXCEL转Strings文件
- 软件工程-第一部分 软件工程介绍
- 特定显示器调整主副屏、方向、位置
- nginx配置location总结及rewrite规则写法
- 解决<span>标签内容改变,不能触发方法的问题
- wpf TreeView绑定