有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

为什么在Android/Java中使用单例类,而同样的功能看起来是通过使用带有静态字段和方法的类来提供的

例如

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;
    }
}

共 (1) 个答案

  1. # 1 楼答案

    这主要是由于static typessingletons的局限性。它们是:

    • 静态类型不能实现接口并从基类派生
    • 从上面我们可以看到,静态类型会导致高度耦合——您不能在测试和不同的环境中使用其他类
    • 不能使用依赖项注入来注入静态类
    • 单身汉更容易模仿和填充
    • 单态可以很容易地转换成瞬态

    这是我头脑中的几个原因。这可能不是全部