Interface implementation hiding method

久未见 提交于 2019-12-13 02:41:51

问题


I need advice on interfaces. I have a class called Unit which can attack other units. The attack can be air or ground. I need single method to achieve attacking called attack(). Some units can only attack ground units, some air units or both.

This is what I've come up so far:

public interface Attack() {
    public void attack(SCObject object);
}

public interface GroundAttack() extends Attack {
    public void groundAttack(SCObject object);
}

public interface AirAttack() extends Attack {
    public void airAttack(SCObject object);
}

I have can have different units:

Unit extends SCObject implements GroundAttack {
}

Unit extends SCObject implements AirAttack {
}

Unit extends SCObject implements AirAttack, GroundAttack {
}

The problem is this implementation will reveal the two ground and air options whereas I only want attack() method to be visible. Can you propose solution or does this seem ok to you?


回答1:


I would use

public interface Attack {
    public boolean canAttack(SCObject object);
    public void attack(SCObject object);
}

I don't see a reason to have a specific ground or air attack method given you didn't want to expose this behaviour.




回答2:


I think the visitor or double-dispatch pattern may apply here, given that the ability to attack depends on interactions between the attacker and victim.

Some form of invocation in which the attacker attacks(), and passes itself as an argument will allow the victim to determine the validity of the attack. Note that this could allow you to change the attackability at runtime (e.g. can a 'ground' unit take to the air?)



来源:https://stackoverflow.com/questions/11932037/interface-implementation-hiding-method

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