DI,Guice和策略模式 [英] DI, Guice and Strategy Pattern
本文介绍了DI,Guice和策略模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下基类,Queen和Knight作为其派生类。 WeaponBehaviour是一个界面。根据具体的GameCharacter类型,我无法弄清楚如何使用Guice注入武器。
Suppose I have the following base class, Queen and Knight as its derivatives. WeaponBehaviour is an interface. I can't figure out how to inject weapons using Guice depending on the concrete GameCharacter type.
public abstract class GameCharacter {
@Inject
protected WeaponBehaviour weapon;
public GameCharacter() {
}
public void fight() {
weapon.useWeapon();
}
public void setWeapon(WeaponBehaviour weapon) {
this.weapon = weapon;
}
}
推荐答案
您可以使用绑定注释。
一个子类:
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);
这篇关于DI,Guice和策略模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文