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

标签 java android singleton

<分区>

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

  • 静态类型不能实现接口(interface)和从基类派生。
  • 从上面我们可以看出,静态类型会导致高耦合——您不能在测试和不同环境中使用其他类。
  • 不能使用依赖注入(inject)来注入(inject)静态类。
  • 单例更容易模拟和 shim。
  • 单例可以很容易地转换为 transient 。

这几个原因来 self 的脑海。这可能还不是全部。

关于java - 单例类与静态方法和字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47325586/

相关文章:

java - GridLayout 上的 JButtons - MineSweeper

android - 备份和恢复 SQLite 数据库到 SD 卡

c# - 在C#中实现单例可继承类

java - 评级栏小部件 Java

java - 字符串长度的差异(数据库 - .txt 文件)

安卓 IAB : "Error refreshing inventory (querying prices of items)" Developer Error

swift - Swift 是否在初始化类的过程中执行该类的方法?

java - 为什么拥有静态嵌套类会导致在不在源代码中时添加第二个构造函数?

java - 如何防止碰撞后 body 移动 [Box2D] [AndEngine]

android - 如何在 Android 中创建像图像一样的进度条