gpt4 book ai didi

java - 单例类与静态方法和字段?

转载 作者:太空宇宙 更新时间:2023-11-03 12:45:26 24 4
gpt4 key购买 nike

<分区>

当使用具有静态字段和方法的类看起来可以提供相同的功能时,为什么要在 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;
}
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com