DI,Guice和战略模式

One*_*mir 0 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*iel 6

您可以使用绑定注释.

子类:

class GimliSonOfGloin extends GameCharacter {

    @Inject
    public void setWeapon(@Axe WeaponBehaviour weapon) {
        super.setWeapon(weapon);
    }
}
Run Code Online (Sandbox Code Playgroud)

注释:

@BindingAnnotation 
@Target({ FIELD, PARAMETER, METHOD }) 
@Retention(RUNTIME)
public @interface Axe {}
Run Code Online (Sandbox Code Playgroud)

绑定:

bind(WeaponBehaviour.class)
    .annotatedWith(Axe.class)
    .to(MyAxe.class);
Run Code Online (Sandbox Code Playgroud)