android 几种单例模式的写法
来源:互联网 发布:socket网络编程视频 编辑:程序博客网 时间:2024/05/29 18:18
首先,先不论单例模式的写法,有些方面是相同的,比如都需要将唯一的对象设置为static的,都需要将构造方法private化,代码如下:
public class MyInstance { private static MyInstance instance; private MyInstance(){}
}
第一种:最原始的单例模式,代码如下:
public static MyInstance getInstance(){ if(instance==null){ instance=new MyInstance(); } return instance; }
多线程并发时,可能会出现重复new对象的情况,因此不提倡使用。
第二种:将整个方法块进行加锁,保证线程安全。public static synchronized MyInstance getInstance(){ if(instance==null){ instance=new MyInstance(); } return instance; }这种代码下,每条线程都会依次进入方法块内部,虽然实现了单例,但是影响了运行效率,可以使用但是也不怎么提倡。
第三种:进一步优化的方法。
public static MyInstance getsInstance(){ synchronized (MyInstance.class){ if(instance==null){ instance=new MyInstance(); return instance; }else{ return instance; } }}这种方式只是第二种方法的一种优化,但是优化有限。
以下的几种方法比较推荐大家使用:
第四种:双层判断加锁,效率影响小且保证了线程安全。
public static MyInstance getsInstance() { if (instance == null) { synchronized (MyInstance.class) { if(instance==null){ instance=new MyInstance(); } } } return instance;}这种方法是在观看闫振杰大神的直播时看到的,顿时感觉相当棒,是对第二种和第三种方法的进一步优化,比较推荐大家使用。
第五种:内部类实现单例,不用线程锁来实现效率的提升。
public class MyInstance { private MyInstance() { } public static MyInstance getInstance(){ return MyInstanceHolder.instance; } private static class MyInstanceHolder{ private static MyInstance instance=new MyInstance();}}在内部类中new对象,再将内部类的对象返回,这种方法是使用了java中class加载时互斥的原理来实现了线程的安全。不加线程锁也使得运行效率不会受到较大的影响。比较提倡。
0 0
- android 几种单例模式的写法
- C++ 几种单例模式的写法
- Android中单例模式的多种写法
- Android 单例模式最好的写法
- 两种单例模式的写法
- 常见的Android中的单利模式的写法
- android单例模式的几种写法,以及优缺点
- Android中Application单例模式的正确写法
- Android开发中单例模式写法与可能遇到的坑
- Android开发中单例模式写法与可能遇到的坑
- Android开发中单例模式写法与可能遇到的坑
- java几种单例模式写法
- Android Widget的写法
- Android.mk的写法
- Android FragmentStatePagerAdapter的写法
- Android Parcelable的写法
- ViewHolder模式的简洁写法
- ViewHolder模式的sparseArray写法
- qt QLayout: Attempting to add QLayout "" to MainWindow "", which already has a layout. 错误
- [Leetcode] 17. Letter Combinations of a Phone Number
- [nginx] location定位
- 矩形内接任意多边形抠图(可以羽化边缘)
- js实现中介者模式
- android 几种单例模式的写法
- 随笔
- JVM参数配置大全
- java基本语法之 javadoc02
- JAVA操作Excel时文字自适应单元格的宽度设置方法
- 状态机思路在程序设计中的应用
- 使用curl进行模拟登录
- 栈
- PAT A1048. Find Coins (25)