赞
踩
实现单利有很多种写法:这里列举几个常见写法,并分析其优劣。
public class Singleton{
private Singleton(){};
private static Singleton mInstance ;
public static newInstance(){
if(mInstance == null){
mInstance = new Singleton();
}
return mInstance;
}
}
public class Singleton{
private staitc Singleton mInstance;
private Singleton(){};
public static synchronized Singleton new Instance(){
if(mInstance == null){
mInstance = new Singleton();
}
return mInstance;
}
}
public class Singleton{
private final static Singleton mInstance = new SingleTon();
private Singleton(){};
public static Singleton newInstance(){
return mInstance;
}
}
public class Singleton {
private static volatile Singleton singleton;
private Singleton() {}mInstance
public static Singleton getInstance() {
if (mInstance == null) {
synchronized (Singleton.class) {
if (mInstance == null) {
mInstance = new Singleton();
}
}
}
return mInstance;
}
}
public class Singleton {
private Singleton() {}
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonInstance.INSTANCE;
}
}
另外还有枚举方式的写法,因为Android不推荐使用单例,这里不再写出。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。