《Android源码设计模式》第二章:Android中所有单例模
2018-04-26 本文已影响27人
ldlywt
/**
* 1.饿汉式
*/
class Singleton_1 {
private static final Singleton_1 ourInstance = new Singleton_1();
static Singleton_1 getInstance() {
return ourInstance;
}
private Singleton_1() {
}
}
/**
* 2.懒汉式
* 优点:只有在使用时才实例化,在一定程度上节省了资源
* 缺点:第一次加载要及时进行实例化,反应稍慢,每次调用getInstance()都进行同步,造成不必要开销
* 一般不建议使用
*/
class Singleton_2 {
private static Singleton_2 instance;
private Singleton_2(){
}
public static synchronized Singleton_2 getInstance(){
if (instance == null) {
instance = new Singleton_2();
}
return instance;
}
}
/**
* 3.DCL实现单例模式
* 优点:资源利用率高,第一次执行getInstance()时单利对象才会被实例化,效率高。
* 缺点:第一次加载反应稍慢,也由于java内存模型的原因偶尔会失败。
* 是使用最多的单例实现方式
*/
class Singleton_3{
private static Singleton_3 instance = null;
private Singleton_3(){
}
public void doSomething(){
//do something
}
public static Singleton_3 getInstance(){
if (instance == null) {
synchronized (Singleton_3.class){
if (instance == null) {
instance = new Singleton_3();
}
}
}
return instance;
}
}
/**
* 4.静态内部类单例模式
* 优点:第一次加载类时不会初始化sInstance,第一次调用方法才会
* 不仅确保线程安全,也能保证单例对象的唯一性,同时延迟了单例的实例化
*/
class Singleton_4{
private Singleton_4(){
}
public static Singleton_4 getInstance() {
return SingletonHolder.sInstance;
}
/**
* 静态内部类
*/
private static class SingletonHolder{
private final static Singleton_4 sInstance = new Singleton_4();
}
}
/**
* 5.枚举单例
* 优点:线程安全,任何时候都只有一个单例,反序列化也不会
*/
public enum SingletonEnum_5{
INSTANCE;
public void doSomething(){
//do something
}
}
使用第四种方式:静态内部类来实现单例相对来说是最好的。