您的位置:首页 > 移动开发 > Android开发

android 几种单例模式的写法

2017-02-12 13:58 716 查看
首先,先不论单例模式的写法,有些方面是相同的,比如都需要将唯一的对象设置为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加载时互斥的原理来实现了线程的安全。不加线程锁也使得运行效率不会受到较大的影响。比较提倡。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  单例模式 android