为什么在Android / Java中使用Singleton类,当使用具有静态字段和方法的类提供相同的功能 时?
e.g。
public class StaticClass {
private static int foo = 0;
public static void setFoo(int f) {
foo = f;
}
public static int getFoo() {
return foo;
}
}
VS
public class SingletonClass implements Serializable {
private static volatile SingletonClass sSoleInstance;
private int foo;
//private constructor.
private SingletonClass(){
//Prevent form the reflection api.
if (sSoleInstance != null){
throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
}
foo = 0;
}
public static SingletonClass getInstance() {
if (sSoleInstance == null) { //if there is no instance available... create new one
synchronized (SingletonClass.class) {
if (sSoleInstance == null) sSoleInstance = new SingletonClass();
}
}
return sSoleInstance;
}
//Make singleton from serialize and deserialize operation.
protected SingletonClass readResolve() {
return getInstance();
}
public void setFoo(int foo) {
this.foo = foo;
}
public int getFoo() {
return foo;
}
}
答案 0 :(得分:5)
这主要是由于static types
与singletons
的限制。这是:
这些原因来自我的头脑。这可能不是全部。