静的フィールドと静的メソッドを持つクラスを使用して同じ機能が提供されているように見えるのに、Android / Javaでシングルトンクラスが使用されるのはなぜですか?
例えば
public class StaticClass {
private static int foo = 0;
public static void setFoo(int f) {
foo = f;
}
public static int getFoo() {
return foo;
}
}
対
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;
}
}
これは主の制限によるものであるstatic types
対singletons
。どれが:
私の頭の上からこれらのいくつかの理由。これはおそらくすべてではありません。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加