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)
您可以使用绑定注释.
子类:
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)
| 归档时间: |
|
| 查看次数: |
929 次 |
| 最近记录: |