android 几种单例模式的写法
2017-02-12 13:58
716 查看
首先,先不论单例模式的写法,有些方面是相同的,比如都需要将唯一的对象设置为static的,都需要将构造方法private化,代码如下:
第一种:最原始的单例模式,代码如下:
多线程并发时,可能会出现重复new对象的情况,因此不提倡使用。
第二种:将整个方法块进行加锁,保证线程安全。
这种代码下,每条线程都会依次进入方法块内部,虽然实现了单例,但是影响了运行效率,可以使用但是也不怎么提倡。
第三种:进一步优化的方法。
这种方式只是第二种方法的一种优化,但是优化有限。
以下的几种方法比较推荐大家使用:
第四种:双层判断加锁,效率影响小且保证了线程安全。
这种方法是在观看闫振杰大神的直播时看到的,顿时感觉相当棒,是对第二种和第三种方法的进一步优化,比较推荐大家使用。
第五种:内部类实现单例,不用线程锁来实现效率的提升。
在内部类中new对象,再将内部类的对象返回,这种方法是使用了java中class加载时互斥的原理来实现了线程的安全。不加线程锁也使得运行效率不会受到较大的影响。比较提倡。
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加载时互斥的原理来实现了线程的安全。不加线程锁也使得运行效率不会受到较大的影响。比较提倡。
相关文章推荐
- android单例模式的几种写法,以及优缺点
- 单例模式的几种写法(包含双检锁写法)
- activity在android中的几种加载模式
- android listview优化几种写法 详细出处参考:http://www.jb51.net/article/31886.htm
- android listview 优化几种写法详细介绍
- android 中文件存储以及几种操作模式
- 单例模式的几种写法(包含双检锁写法)
- 单例模式的几种写法
- Android系统手机几种运行模式解析
- android listview优化几种写法详细介绍
- Android listview优化几种写法详细介绍
- Android系统手机几种运行模式分析
- C++ 几种单例模式的写法
- 关于Android Activity 的几种模式
- Android夜间模式的几种实现
- 单例模式的几种写法(包含双检锁写法)
- Android Handler的几种写法
- Android多线程的几种模式备忘
- android几种常见的启动模式
- C++中几种常见的单例模式写法。