http://xyiyy.iteye.com/blog/359362
1. 首先定义一个抽象类,在类中定义了start()方法,其中实现了比大小的规则,但并没有实现如何取得使用者输入和信息的显示方式,只先定义了抽象方法showMessage()与getUserInput()。
- {
- private int number;
- public void setNumber(int number)
- {
- this.number = number;
- }
- public void start()
- {
- showMessage("欢迎");
- int guess = 0;
- do{
- guess = getUserInput();
- if(guess > number)
- {
- showMessage("输入的数字较大");
- }
- else if(guess < number)
- {
- showMessage("输入的数字较小");
- }
- else
- showMessage("猜中了");
- }while(guess != number);
- }
- protected abstract void showMessage(String message);
- protected abstract int getUserInput();
- }
2.使用AbstractGuessGame类的办法是扩展它,并实现其中的抽象方法。如下面的TextModeGame类:
- import java.util.Scanner;
- public class TextModeGame extends AbstractGuessGame
- {
- private Scanner scanner;
- public TextModeGame()
- {
- scanner = new Scanner(System.in);
- }
- protected void showMessage(String message)
- {
- for(int i = 0; i < message.length()*2;i++)
- System.out.print("*");
- System.out.println("\n" + message);
- for(int i = 0; i < message.length()*2;i++)
- System.out.print("*");
- }
- protected int getUserInput()
- {
- System.out.print("\n请输入数字:");
- return scanner.nextInt();
- }
- }
3.启动游戏的示范类:
- {
- public static void main(String[] args)
- {
- AbstractGuessGame guessGame = new TextModeGame();
- guessGame.setNumber(50);
- guessGame.start();
- }
- }