DI, Guice and Strategy Pattern

白昼怎懂夜的黑 提交于 2019-12-08 10:56:03

问题


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;
    }
}

回答1:


You could use Binding Annotations.

A subclass:

class GimliSonOfGloin extends GameCharacter {

    @Inject
    public void setWeapon(@Axe WeaponBehaviour weapon) {
        super.setWeapon(weapon);
    }
}

The Annotation:

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

The Binding:

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


来源:https://stackoverflow.com/questions/11667134/di-guice-and-strategy-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!