我是
Guice DI
的新人。我正在尝试使用 Strategy
实现 Guice
模式。但我对如何通过Context
在Guice DI
类中注入不同类型的策略实现感到困惑。有哪位专家可以帮我解决这个问题吗?以下是我到目前为止的代码。
策略模式
public interface MetricCollectorStrategy {
List<String> collect(final Context context);
}
public class AMetricCollector implements MetricCollectorStrategy {
@Override
public List<String> collect(final Context context) {
List<String> aMetricList = construct A metric list by some business logic....
return aMetricList;
}
}
public class BMetricCollector implements MetricCollectorStrategy {
@Override
public List<String> collect(final Context context) {
List<String> bMetricList = construct B metric list by some business logic....
return bMetricList;
}
}
@AllArgsConstructor(onConstructor_ = @Inject)
public class MetricPublisher {
// This has a method to publish metric
private final MetricsHelper metricsHelper;
private final MetricCollectorStrategy metricCollectorStrategy;
public void collectAndPublishMetric(Context context) {
metricsHelper.emitCollectedCountMetricList(metricCollectorStrategy.collect(context));
}
}
到那时就可以了。但是如何在客户端创建并注入这两种类型的
MetricCollector
:
@AllArgsConstructor(onConstructor_ = @Inject)
public class Client{
// Some dummy code to simulate the current code
private final ExistingDependency_1 existingDependency_1;
private final ExistingDependency_2 existingDependency_2;
private final ExistingDependency_3 existingDependency_2;
// Now how to create the metricCollectors here
AMetricCollector aMetricCollector;
BMetricCollector bMetricCollector;
public void someMethod(Context context){
if(condition){
aMetricCollector.collectAndPublishMetric(context);
}else{
bMetricCollector.collectAndPublishMetric(context);
}
}
}
注意你说的地方
// Now how to create the metricCollectors here
不是您实际应该创建 metricCollectors 的地方。这就是依赖注入的要点,您注入依赖项而不是构建它们。
您应该有一个构造函数来接收这些依赖项,并且您的 DI 框架应该创建它们。