Appearance
命令模式
定义
命令模式(Command Pattern)是一种行为设计模式,它将请求封装为一个对象,从而允许你使用不同的请求、队列请求或记录请求日志,并支持可撤销的操作。
使用场景
- 当你需要将请求封装为一个对象时,可以使用命令模式。这样可以将请求与执行请求的对象解耦,使得请求可以更灵活地被处理。
- 当你需要支持撤销操作时,可以使用命令模式。通过将请求封装为一个对象,可以在需要时撤销请求。
优点
- 将请求封装为对象,使得请求可以更灵活地被处理。
- 支持撤销操作,可以通过记录请求日志来实现。
- 可以实现请求的队列处理和日志记录。
代码示例
java
public interface Command {
void execute();
}
public class GamePane {
private boolean playing;
void start() {
if (!playing) {
System.out.println("开始游戏...");
playing = true;
}
}
void stop() {
if (playing) {
System.out.println("停止游戏...");
playing = false;
}
}
}
public class StartGame implements Command{
private final GamePane gamePane;
public StartGame(GamePane gamePane) {
this.gamePane = gamePane;
}
@Override
public void execute() {
gamePane.start();
}
}
public class StopGame implements Command{
private final GamePane gamePane;
public StopGame(GamePane gamePane) {
this.gamePane = gamePane;
}
@Override
public void execute() {
gamePane.stop();
}
}
public class GameControl {
private final Map<String, Command> commands;
public GameControl() {
this.commands = new HashMap<>();
}
public void addCommand(String name, Command command) {
commands.put(name, command);
}
public void removeCommand(String name) {
commands.remove(name);
}
public void receiveCommand(String name) {
commands.get(name).execute();
}
}
java
public class Client {
public static void main(String[] args) {
GamePane gamePane = new GamePane();
StartGame startGame = new StartGame(gamePane);
StopGame stopGame = new StopGame(gamePane);
GameControl gameControl = new GameControl();
gameControl.addCommand("start", startGame);
gameControl.addCommand("stop", stopGame);
gameControl.receiveCommand("start");
gameControl.receiveCommand("stop");
}
}
运行结果
txt
开始游戏...
停止游戏...