设计原则之城堡游戏(下)

@spiritree  August 25, 2016

制造Handler类(框架+数据)以及它的子类来加强可扩展性

  • 命令的解析脱离if-else

  • 定义一个Handler来处理命令

  • 用Hash表来保存命令和Handler之间的关系

Handler类及其子类

public class Handler {
    protected Game game;

    public Handler(Game game) {
        this.game = game;
    }

    public void doCmd(String word) {    //cmd=command
    }
    public boolean isBye() {
        return false;
    }
}
public class HandlerBye extends Handler {
    public HandlerBye(Game game) {
        super(game);
    }

    @Override
    public boolean isBye() {
        return true;
    }
}
public class HandlerGo extends Handler {
    public HandlerGo(Game game) {
        super(game);
    }

    @Override
    public void doCmd(String word) {
        game.goRoom(word);
    }
}
public class HandlerHelp extends Handler {
    public HandlerHelp(Game game) {
        super(game);
    }

    @Override
    public void doCmd(String word) {
        System.out.println("迷路了吗?你可以做的命令有:go bye help");
        System.out.println("如:\tgo east");
    }
}

添加新评论