我可以使用Dagger将不同的值注入到对象图中深处的同一类的多个实例中吗?我想避免通过图中的包含对象传递值(这样我就可以更改包含对象的实现而不影响它们的容器)。
这是一个人为的例子。对象图是一个 Top,它包含一个 Left 和 Right,每个都包含一个 Show。所以有两个 Show 实例。
class Top {
Left left;
Right right;
void encodeTwice(String data) {
left.encode(data);
right.encode(data.getBytes());
}
}
class Left {
Leaf leaf;
void encode(String data) {
leaf.write(URLEncoder.encode(data));
}
}
class Right {
Leaf leaf;
void encode(byte[] data) {
leaf.write(DatatypeConverter.printBase64Binary(data));
}
}
interface Leaf {
void write(String data);
}
class Show implements Leaf {
String label;
@Override public void write(String data) {
System.out.println(label + ": " + data);
}
}
// There might be other classes that implement Leaf.
我可以使用 Dagger 向 Top.left.leaf.label 和 Top.right.leaf.label 注入不同的值吗?
这是一个尝试。这是不能令人满意的,因为 Left 和 Right 依赖于 Leaf 的实现。我想在不涉及 Left 或 Right 的情况下注入 Show.label。
ObjectGraph.create(new TopModule()).get(Top.class).encodeTwice("Hello!");
@Module(injects = Top.class)
public class TopModule {
@Provides @Named("Left.leaf.label") String provideLeftLabel() {
return "URL encoded";
}
@Provides @Named("Right.leaf.label") String provideRightLabel() {
return "Base 64";
}
}
class Top {
@Inject Left left;
@Inject Right right;
void encodeTwice(String data) {
left.encode(data);
right.encode(data.getBytes());
}
}
class Left {
Leaf leaf;
@Inject Left(@Named("Left.leaf.label") String label) {
leaf = new Show(label);
}
void encode(String data) {
leaf.write(URLEncoder.encode(data));
}
}
class Right {
Leaf leaf;
@Inject Right(@Named("Right.leaf.label") String label) {
leaf = new Show(label);
}
void encode(byte[] data) {
leaf.write(DatatypeConverter.printBase64Binary(data));
}
}
interface Leaf {
void write(String data);
}
class Show implements Leaf {
String label;
Show(String label) {
this.label = label;
}
@Override public void write(String data) {
System.out.println(label + ": " + data);
}
}