gpt4 book ai didi

java - 使用 DI 时如何处理对象的特殊 "constant"实例

转载 作者:行者123 更新时间:2023-11-29 09:06:57 25 4
gpt4 key购买 nike

我的项目大量使用依赖注入(inject),我非常小心地避免服务定位器反模式。所有对象都使用构造函数注入(inject)构造,允许轻松识别依赖项列表。现在我正在构建一个对象,它有一个特殊的“常量”实例,它基本上是静态/单例的(考虑像 Integer.MinValue 这样的例子)。所以我最初的 react 是创建一个带有静态“getter”方法的静态字段,如果之前没有创建该对象的实例,它将创建该对象的实例。然而,对象本身具有依赖性,所以我对实例化这个“特殊实例”的最佳实践感到困惑。我正在寻找有关如何在这种情况下最好地构建代码的建议,理想情况下无需调用容器来解决依赖关系。一些代码:

public class PressureUnit extends DataUnit {
private static PressureUnit standardAtmosphere;
public static PressureUnit StandardAtmosphere() {
if(standardAtmosphere == null){
standardAtmosphere = new PressureUnit(1013.25); // this line is what is bothering me as I need to resolve other dependencies (have to use new as it's a static method and can't be injected like everywhere else)
}
return standardAtmosphere;
}

@AssistedInject
public PressureUnit(ITimeProvider timeProvider, IUnitProvider unitProvider, @Assisted double value) {
this(timeProvider, unitProvider, value, PressureUnits.hPa);
}
...
}

最佳答案

我真的没有在你的代码中看到任何问题,因为你没有在这里和那里更新依赖关系,现在我可以给出一些建议:

  • 如果你特别希望容器调用现有的静态工厂方法,你可以使用StaticFactoryExtension。 .
  • 你为什么不使用工厂。
  • 考虑重构您的设计并在可能的情况下删除静态方法。

关于java - 使用 DI 时如何处理对象的特殊 "constant"实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14465624/

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