典型单例的写法
class Singleton {
private static volatile Singleton instance = null;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
另一种优美的写法,利用静态变量
class Singleton {
private static class SingletonHolder {
private static Singleton instance = new Singleton();
}
public Singleton getInstance(){
return SingletonHolder.instance;
}
}
更加优美的写法(android慎用)
enum Singleton {
INSTANCE;
public Singleton getInstance(){
return INSTANCE;
}
}