这是本博看了《android源码设计模式解析与实战》的总结。
单例模式的实现方式
1.懒汉模式

public class Singleton{
 private static  Singleton sInstance;
 private Singleton(){
 }
public static synchronized Singleton getInstance(){
if(sInstance == null){
sInstance = new Singleton();
}
return sInstance;
}
}

缺点: 每次获取instance都要进行同步,比较消耗资源。

2.饿汉模式

public class Singleton{
 private static  Singleton sInstance = new Singleton();
 private Singleton(){
 }
public static  Singleton getInstance(){
return sInstance;
}
}

3.DCL double check lock 双重判断模式

public class Singleton{
 private static  Singleton sInstance;
 private Singleton(){
 }
public static  Singleton getInstance(){
if(sInstance == null){
synchronized(Singleton.class){
if(sInstance == null){
sInstance = new Singleton();
}
}
}
return sInstance;
}
}

android中的单例模式
4.推荐的模式1:

public class Singleton{
private Singleton(){
}
public static Singleton getInstance(){
return SingleHolder.instance;
}
private static class  SingleHolder{
private static final  Singleton instance = new Singleton();
}
}

android中的单例模式
5.客户端一般没有高并发场景,所以后两种都推荐使用

相关文章: