单例模式
2015-12-07 17:04
281 查看
第一种(懒汉,线程不安全):
这种方法在多线程的情况下不能工作public class Singleton { private static Singleton instance; private Singleton (){} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
第二种(懒汉,线程安全):
这种方法在多线程中可以工作,但是直线效率比较低,在我们实际开发中有绝大部分的情况下是不需要同步的public class Singleton { private static Singleton instance; private Singleton (){} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
第三种(饿汉):
这种方式基于classloder机制避免了多线程的同步问题,不过,instance在类装载时就实例化,虽然导致类装载的原因有很多种,在单例模式中大多数都是调用getInstance方法, 但是也不能确定有其他的方式(或者其他的静态方法)导致类装载,这时候初始化instance显然没有达到lazyloading的效果。
public class Singleton { private static Singleton instance = new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; } }
第四种(饿汉,变种):
public class Singleton { private Singleton instance = null; static { instance = new Singleton(); } private Singleton (){} public static Singleton getInstance() { return this.instance; } }
第六种(枚举):
public enum Singleton { INSTANCE; public void whateverMethod() { } }
第七种(双重校验锁):
public class Singleton { private volatile static Singleton singleton; private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
相关文章推荐
- Python学习记录
- Android开发中适配多种 ROM 的快捷方式是如何实现的?
- Git入门私房菜
- knn之构造kd树和最近邻求取c++实现
- 面向对象编程 下
- 第十五周 项目二(2) 用哈希法组织关键字
- 第十三周项目4—Floyd算法的验证
- 第十二周项目1-图基本算法库
- ListView中convertView和ViewHolder的工作原理
- Canvas的save和restore
- usb调试停用系统应用-利用adb命令
- 双11大促期间,作为一个测试人员的反思
- Python-面向对象编程(二)
- 第十五周——【项目3 - B-树的基本操作】(选看)
- django项目中的数据库中增加数据
- poi 1017 Packets 贪心+模拟
- sourceInsight 快速插入时间
- 第十五周 项目3 希尔排序
- 第十三周 项目 验证算法 运行并本周视频中所讲的的算法,观察结果并领会算法
- 快学Scala读书笔记之Chapter12(高阶函数)、Chapter13(集合)