我有一個類A
,與List<String>
一起使用。但是這個類以外的人都不需要知道它可以和字符串一起工作。但是,我也想提供類應該使用的具體實現List
(通過依賴注入)。依賴注射收藏
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();
//...
}
}
而且這樣
public class B {
public void b() {
ListFactory factory = new ArrayListFactory(); //we want class A to use ArrayList
A a = new A(factory);
//...
}
}
ListFactory
主叫類B
東西會是由ArrayListFactory
實現創建ArrayList
秒的接口。
精髓: 我不希望B
就不能不提String
地方。而且我也不希望A
在某處不得不提及ArrayList
。
這可能嗎? ListFactory
和ArrayListFactory
怎麼樣?
哇。謝謝!我甚至不知道這種語法。不得不看這個......這正是我想要的 – qollin
不錯,我錯過了。 –