【问题标题】:Singleton class vs static methods and fields? [duplicate]单例类与静态方法和字段? [复制]
【发布时间】:2018-04-29 18:01:36
【问题描述】:

为什么在 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;
    }
}

【问题讨论】:

  • 请通过This 关于 SO 的讨论。如果你还没有!
  • 谢谢,我应该删除这个问题吗?
  • 这是一个合理的问题。但是所有的讨论都已经在我提到的线程中进行了。所以只需将其标记为重复。

标签: java android singleton


【解决方案1】:

这主要是由于static typessingletons 的限制。分别是:

  • 静态类型不能实现接口和从基类派生。
  • 从上面我们可以看出,静态类型会导致高耦合——你不能在测试和不同的环境中使用其他类。
  • 不能使用依赖注入来注入静态类。
  • Singleton 更容易模拟和填充。
  • 单例可以轻松转换为瞬态。

我想到了这几个原因。这可能还不是全部。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 2011-05-17
    • 2017-07-15
    • 2013-08-19
    • 2014-02-14
    • 1970-01-01
    相关资源
    最近更新 更多