我会说你不应该使用接口。更好的方法是使用超类。使用超类,您可以避免重新定义许多可能由对手和英雄共享的方法。这是一个示例实现:
超类:
public abstract class ExampleFighter {
private String name;
private int health;
private boolean isDead = false;
public ExampleFighter(String name, int health) {
this.name = name;
this.health = health;
}
public void attack(ExampleFighter ef) {
int damage = 0;
//calculate damage dealt
damage = 10;
ef.takeDamage(damage);
}
public void takeDamage(int damage) {
//manipulate the amount of damage taken
if(health - damage <= 0) {
health = 0;
isDead = true;
} else {
health -= damage;
}
}
public boolean isDead() {
return isDead;
}
}
子类:
public class ExampleHero extends ExampleFighter {
int reputation; //the general opinion of the hero
public ExampleHero() {
super("Hero Oreh of Herosville", 100);
reputation = 0;
}
public void improveReputation() {
reputation++;
}
}
public class ExampleRival extends ExampleFighter {
public ExampleRival() {
super("Your greatest rival", 101);
}
}
这个系统的副作用是它需要第四个班级才能真正玩游戏:
public class ExampleGame {
private ExampleHero hero;
private ExampleRival rival;
public static void main(String... args) {
ExampleGame game = new ExampleGame();
game.start();
}
public ExampleGame() {
hero = new ExampleHero();
rival = new ExampleRival();
//what ever other game setup you need to do.
//alternately you could have a load() method
//that takes care of most of this.
}
private void start() {
//make your run loop or query the user for input
//or whatever you need to do. I will create an
//example run loop
boolean running = true;
while(running) {
//this whole block should be moved
//to another method called gameUpdate()
//or something similar but since this
//is a quick example I'll just leave it
//here
hero.attack(rival);
rival.attack(hero);
if(rival.isDead()) {
hero.improveReputation();
System.out.println(“Your rival is dead!");
running = false;
} else if(hero.isDead()) {
System.out.println("you died :(");
running = false;
}
}
}
}
现在这可能看起来有点复杂,但它说明了一个非常重要的概念:关注点分离。关注点分离包括放置代码和制作有意义的类。玩家不应该知道它的对手是谁,玩家甚至可能不知道敌人的存在或者它站在什么样的地形上。但是玩家应该知道如何管理它的生命值、它的名字、如何受到伤害等。相比之下,一个游戏对象需要知道所有玩家和敌人,这样它才能告诉他们在屏幕上战斗和移动。这是关注点分离的非正式定义,有关更准确的信息,请阅读wikipedia page。在这个例子中,我将英雄和对手分开,这样以后你就可以添加更多的敌人,而不必每次都修改你的英雄代码。该系统还允许您在不影响玩家或对手的情况下扩展游戏的 UI。如果你想为你的游戏添加一个 GUI,你可以在 ExampleGame 中添加一个用于设置 GUI 的 initialize() 方法。然后在游戏循环中,您可以调用方法将图像和图形绘制到 GUI 上。通过分离关注点,您可以使系统更加模块化和易于使用。
您的第二个问题是:我们为什么要使用接口?接口是一种确保其他类具有您需要它们具有的行为的方法,而无需具体指定它们应该如何做。使用接口的一个经典例子是 Comparable 接口。 Comparable 接口有一个必须实现的方法:compareTo()。此方法的目的是允许对不能使用标准布尔数学运算(、== 等)的值对象(想想 String 或 File)进行排名。您可以将其视为签署合同。您(实现该接口的类)同意拥有一组特定的功能,但是您是否决定该功能取决于您。更多信息请阅读java tutorial
我应该在这个答案中添加一个警告:继承不是 最佳 选项。如果您想知道如何正确操作,您应该查找MVC (Model View Controller) 和Component Based Design。即使这些可能不是您正在做的事情的最佳选择,但它们是很好的起点。