命令模式(Command Pattern)是一种行为型设计模式,它将请求(或命令)封装成一个对象,从而使你可以将请求的发送者和接收者解耦。命令模式通过将请求封装为对象,可以让你在不同时间对请求进行处理、撤销、重做等操作。
个人理解:定义一个命令,不同的操作实现该命令,有一个统一管理类来协调调用不同的操作。
在命令模式中,通常有以下几个角色:
- 命令(Command):定义了一个执行操作的接口,所有的具体命令类都实现该接口。
- 具体命令(ConcreteCommand):实现命令接口,负责调用接收者的相应操作。
- 接收者(Receiver):知道如何实施与执行一个请求相关的操作,这些操作的主体。
- 调用者(Invoker):请求命令执行的类,它持有一个命令对象并在适当的时候调用命令的
execute()方法,需求方,也就是统一管理类。 - 客户端(Client):创建一个具体的命令对象,并设置其接收者, 3所说的具体接收者。
示例
在游戏中控制玩家角色执行不同的动作,比如移动角色、攻击、跳跃等。我们可以使用命令模式来解耦这些操作的触发和执行逻辑。
// 1. 命令接口
class Command {
execute() {}
}
// 2. 接收者 - 游戏角色
class Character {
move() {
console.log('角色移动.');
}
jump() {
console.log('角色跳跃.');
}
attack() {
console.log('角色攻击.');
}
}
// 3. 具体命令类
class MoveCommand extends Command {
constructor(character) {
super();
this.character = character;
}
execute() {
this.character.move();
}
}
class JumpCommand extends Command {
constructor(character) {
super();
this.character = character;
}
execute() {
this.character.jump();
}
}
class AttackCommand extends Command {
constructor(character) {
super();
this.character = character;
}
execute() {
this.character.attack();
}
}
// 4. 调用者 - 游戏控制器
class GameController {
constructor() {
this.command = [];
}
setCommand(command) {
this.command.push(command);
}
executeCommand() {
let cmd = this.command.pop();
if (cmd) {
cmd.execute();
} else{
console.log('没有命令.');
}
}
}
// 5. 客户端 - 设置和触发命令
const player = new Character();
const moveCommand = new MoveCommand(player);
const jumpCommand = new JumpCommand(player);
const attackCommand = new AttackCommand(player);
const gameController = new GameController();
gameController.setCommand(moveCommand);
gameController.executeCommand(); // 输出: 角色移动.
gameController.setCommand(jumpCommand);
gameController.executeCommand(); // 输出: 角色跳跃.
gameController.setCommand(attackCommand);
gameController.executeCommand(); // 输出: 角色攻击.
gameController.executeCommand(); // 输出: 没有命令.
总结
命令模式在游戏开发中非常适用,尤其是当需要处理玩家输入、操作队列、实现操作撤销/重做等功能时。通过使用命令模式,我们可以将各个操作封装成命令对象,轻松扩展并管理它们,同时保持代码的清晰和解耦。