java - 单例如何隐藏其依赖关系?

标签 java singleton

最近我读了the blog post关于单例的缺点,作者指出:

Why is Singleton evil?

  1. Hides dependencies – A component that uses one or more singletons is hiding crucial information about your dependencies. It doesn’t take long for calls to a singleton to creep through your code base like kudzu, slowly attaching itself to every class in the system. Exposing that dependency forces you to think about it as you use a component. It also makes it more reusable as the caller can understand its requirements and how they might be satisfied.

单例究竟是如何隐藏其依赖关系的,这意味着什么?首先我想到了无法注入(inject)依赖项,但我们仍然有 setter 注入(inject),所以它没有意义。

请尽可能提供代码示例。

最佳答案

1 单例可以有一个setter,但它有一个全局的状态。因此,您可以在应用程序的一个地方设置一个对象,它会影响应用程序另一个地方的行为。

2 当你创建一个对象时,你不知道它的依赖关系,因为构造函数没有它们,你只需要编写 new MyObject();

但是里面有另一个对象的依赖关系。而且您对依赖对象状态一无所知。

public class MyObject {

     private AnotherObject anotherObject = Singleton.getInstance(); 

     public MyObject() {
         //nothing here 
     }
}

相反,这样写更有用:

public class MyObject {

    private AnotherObject anotherObject;

    public MyObject(AnotherObject comesFromOutside) {
        this.anotherObject = comesFromOutside;
    }
}

然后您的代码的用户将立即看到您的所有依赖项,而无需查看您的源代码,只需编写 new MyObject(new AnotherObject())

这里有更多信息: http://www.yegor256.com/2016/06/27/singletons-must-die.html

关于java - 单例如何隐藏其依赖关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48243618/

相关文章:

java - RuntimeException : org. hibernate.exception.SQLGrammarException:无法执行查询

java - 使用单例或新对象实例有什么区别吗?

java - 如何解决 LI_LAZY_INIT_UPDATE_STATIC?

java - Android - 每隔几秒改变球的颜色

java - JSON Java 将空数组添加到 JSON 对象

java - 使用 JPA 避免结果列表中的重复项

ios - 即使设置委托(delegate)后协议(protocol)也不起作用

ios - 使用单例创建基本样式助手类

singleton - SqlConnection 单例

java - 列出 Android 中所有可用的通知铃声