10.10
软件设计 石家庄铁道大学信息学院
实验16:命令模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解命令模式的动机,掌握该模式的结构;
2、能够利用命令模式解决实际问题。
[实验任务一]:多次撤销和重复的命令模式
某系统需要提供一个命令集合(注:可以使用链表,栈等集合对象实现),用于存储一系列命令对象,并通过该命令集合实现多次undo()和redo()操作,可以使用加法运算来模拟实现。
实验要求:
1. 提交类图;
2. 提交源代码;
import java.util.Stack;
// Command 接口
interface Command {
void execute();
void undo();
}
// Receiver 类
class Receiver {
private int value;
public void action(int value) {
this.value = value;
System.out.println("Receiver: Action called with value " + value);
}
public int getValue() {
return value;
}
}
// ConcreteCommand 类
class ConcreteCommand implements Command {
private Receiver receiver;
private int value;
public ConcreteCommand(Receiver receiver, int value) {
this.receiver = receiver;
this.value = value;
}
@Override
public void execute() {
receiver.action(value);
}
@Override
public void undo() {
receiver.action(0); // 假设撤销操作是将值设为0
}
}
// Invoker 类
class Invoker {
private Stack<Command> commandHistory = new Stack<>();
private Stack<Command> undoHistory = new Stack<>();
public void storeAndExecute(Command command) {
command.execute();
commandHistory.push(command);
undoHistory.clear(); // 每次执行新命令时,清空重做栈
}
public void undo() {
if (!commandHistory.isEmpty()) {
Command command = commandHistory.pop();
command.undo();
undoHistory.push(command);
}
}
public void redo() {
if (!undoHistory.isEmpty()) {
Command command = undoHistory.pop();
command.execute();
commandHistory.push(command);
}
}
}
// 客户端代码
public class CommandPatternDemo {
public static void main(String[] args) {
Receiver receiver = new Receiver();
Invoker invoker = new Invoker();
Command command1 = new ConcreteCommand(receiver, 5);
Command command2 = new ConcreteCommand(receiver, 10);
Command command3 = new ConcreteCommand(receiver, 15);
invoker.storeAndExecute(command1);
invoker.storeAndExecute(command2);
invoker.storeAndExecute(command3);
invoker.undo(); // 撤销到 command1
invoker.redo(); // 重做到 command3
}
}
3. 注意编程规范。

浙公网安备 33010602011771号