DI,Guice和战略模式

假设我有以下基类,Queen和Knight作为它的衍生物。 WeaponBehaviour是一个界面。 根据具体的GameCharacter类型,我无法弄清楚如何使用Guice注入武器。

public abstract class GameCharacter { @Inject protected WeaponBehaviour weapon; public GameCharacter() { } public void fight() { weapon.useWeapon(); } public void setWeapon(WeaponBehaviour weapon) { this.weapon = weapon; } } 

您可以使用Binding Annotations 。

子类:

 class GimliSonOfGloin extends GameCharacter { @Inject public void setWeapon(@Axe WeaponBehaviour weapon) { super.setWeapon(weapon); } } 

注释:

 @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface Axe {} 

绑定:

 bind(WeaponBehaviour.class) .annotatedWith(Axe.class) .to(MyAxe.class);