java - 集合的依赖注入(inject)

标签 java generics dependency-injection

我有课A适用于 List<String> 。但是这个类之外的任何人都不需要知道它适用于字符串。但是,我还想提供该类应该使用的具体实现,因为它是 List (通过依赖注入(inject))。

A应该看起来像这样

public class A {
  private ListFactory listFactory; //this gets injected from the outside

  public A(ListFactory listFactory) {
    this.listFactory = listFactory;
  }

  public void a() {
    List<String> = listFactory.createList();
    //...
  }
}

以及调用者类B像这样的东西

public class B {
  public void b() {
    ListFactory factory = new ArrayListFactory(); //we want class A to use ArrayList
    A a = new A(factory);
    //...
  }
}

ListFactory将是由 ArrayListFactory 实现的接口(interface)创建ArrayList s。

精髓: 我不想要那个B不得不提String某处。我也不想要那个A不得不提ArrayList某处。

这可能吗?那么ListFactory会怎样呢?和ArrayListFactory必须看吗?

最佳答案

我认为这比你做的要简单:

public interface Factory {
    public <T> List<T> create();
}

public class FactoryImpl implements Factory {
    public <T> ArrayList<T> create() {
        return new ArrayList<T>();
    }
}

...
Factory f = new FactoryImpl();
List<String> strings = f.create();
...

关于java - 集合的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6611881/

相关文章:

java - 模块 jrt.fs 和模块 java.base 中的 RuntimeException : Package jdk. internal.jimage.decompressor

java - JSF 2.0 : <f:viewParam> and default converters

java - 创建类型为 "Class"的参数化类型

asp.net-mvc-3 - ASP.NET MVC3 - 使用 DependencyResolver 和温莎城堡 : Why?

Ruby 依赖注入(inject)库

java - 在 Java 中释放自阻塞引用

java - Apache Helix 资源平衡器(案例 : each resource on independent node)

c# - 拦截通过 DynamicProxy 返回通用 Task<> 的异步方法

c# - 将 Func<T, string>[] 转换成 Func<T, string[]>?

c# - 尝试应用良好的依赖注入(inject)实践时遇到的问题