我會說你不應該使用一個接口。更好的方法是使用超類。有了超類,你可以避免重新定義可能會被敵手和英雄共享的許多方法。下面是一個示例實現:
超類:
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。在這個例子中,我將英雄和對手分開,以便以後可以添加更多的敵人,而不必每次修改英雄代碼。該系統還可以讓您在不影響玩家或對手的情況下擴展遊戲的用戶界面。如果你想添加一個GUI到遊戲中,你可以在ExampleGame中添加一個initialize()方法來設置GUI。然後在遊戲循環中,您可以調用將圖像和圖形繪製到GUI上的方法。隨着擔心的分離,您可以使系統更加模塊化,易於使用。
你的第二個問題是:爲什麼我們要使用接口?接口是確保其他類具有您需要它們的行爲的一種方式,而無需詳細說明應該如何執行它。一個使用接口的經典例子是Comparable接口。 Comparable接口有一個必須實現的方法:compareTo()。此方法的目的是允許對無法使用標準布爾數學運算(<,>,==等)的值對象(思考字符串或文件)進行排序。您可以將其視爲像簽署合同一樣。您(實現該接口的類)同意擁有一組特定的功能,但是您可以根據自己的實際情況制定該功能。欲瞭解更多信息,請閱讀java tutorial
我要告誡添加到這樣的回答:繼承是不是最佳選擇。如果你想知道如何去做,你應該看看MVC (Model View Controller)和Component Based Design。即使這些可能不是你正在做的最好的選擇,但他們是很好的起點。
-1 ..兩個類應以「class」和小寫public爲前綴。 – 2011-06-08 05:02:26