简体   繁体   English

接口实现隐藏方法

[英]Interface implementation hiding method

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() . 我需要一种称为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. 问题在于此实现将显示两个地面选项和空中选项,而我只希望attack()方法可见。 Can you propose solution or does this seem ok to you? 您可以提出解决方案吗?

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. 考虑到您不想暴露这种行为,我认为没有理由采用特定的地面或空袭方法。

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. 攻击者以某种形式的攻击attacks()并将其自身作为参数传递,将使受害者确定攻击的有效性。 Note that this could allow you to change the attackability at runtime (eg can a 'ground' unit take to the air?) 请注意,这可以让您在运行时更改可攻击性(例如,“地面”部队可以空袭吗?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM