文章

命令模式

命令模式是一种行为型模式,它用于将一个请求封装成一个对象,从而允许请求的参数化、记录请求日志、支持撤销操作等。在游戏设计中,命令模式通常用于处理玩家的输入事件,例如按下键盘或鼠标按钮等。下面是一个简单的命令模式的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public interface Command {
    void execute();
    void undo();
}

public class MoveCommand implements Command {
    private Player player;
    private int x;
    private int y;
    
    public MoveCommand(Player player, int x, int y) {
        this.player = player;
        this.x = x;
        this.y = y;
    }
    
    public void execute() {
        player.move(x, y);
    }
    
    public void undo() {
        player.move(-x, -y);
    }
}

public class InputHandler {
    private Command moveUpCommand;
    private Command moveDownCommand;
    private Command moveLeftCommand;
    private Command moveRightCommand;
    
    public InputHandler(Player player) {
        moveUpCommand = new MoveCommand(player, 0, -1);
        moveDownCommand = new MoveCommand(player, 0, 1);
        moveLeftCommand = new MoveCommand(player, -1, 0);
        moveRightCommand = new MoveCommand(player, 1, 0);
    }
    
    public void handleInput(Input input) {
        switch(input) {
            case UP:
                moveUpCommand.execute();
                break;
            case DOWN:
                moveDownCommand.execute();
                break;
            case LEFT:
                moveLeftCommand.execute();
                break;
            case RIGHT:
                moveRightCommand.execute();
                break;
            default:
                break;
        }
    }
}

在这个示例中,Command 是一个接口,它定义了 execute() 和 undo() 方法。MoveCommand 是一个具体的命令类,它封装了玩家的移动请求。InputHandler 是一个命令模式的调用者,它根据输入事件来执行相应的命令。这种方式可以将玩家的输入事件与具体的操作分离开来,方便维护和修改。

本文由作者按照 CC BY 4.0 进行授权