DI,Guice和战略模式

时间:2012-07-26 10:13:09

标签: java dependency-injection guice strategy-pattern

假设我有以下基类,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;
    }
}

1 个答案:

答案 0 :(得分:6)

您可以使用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);