开发者

Java Guice: Run time dependency re-wiring

I have several classes StrategyAlpha, StrategyBeta, StrategyOmega that inherit from the Strategy class.

I would like to select the proper child Strategy depending on property of inputs using guice, the dependency injection framework.

Is wiring the dependencies at runtime a bad idea? How can use开发者_如何学Go Guice to do this?


You'd want to bind something like a StrategyProvider which, given inputs, returns the appropriate strategy.

You could always create a provider - something like:

@Inject StrategyProvider(@Named("alpha") Strategy alpha, @Named("beta") Strategy beta...) { this.alpha = alpha; this.beta = beta; }

Strategy get(Parameter a, parameter b) { if (a > 3 && b < 10) { return beta; } else { return alpha; } }

What the params are, and why would determine whether this makes sense, more than likely.


Looks like what you need is a factory to instantiate appropriate object depending on a set of properties.

You can implement the factory using factory design pattern - http://en.wikipedia.org/wiki/Factory_method_pattern

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜