10.6
软件设计 石家庄铁道大学信息学院
实验16:命令模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解命令模式的动机,掌握该模式的结构;
2、能够利用命令模式解决实际问题。
[实验任务一]:多次撤销和重复的命令模式
某系统需要提供一个命令集合(注:可以使用链表,栈等集合对象实现),用于存储一系列命令对象,并通过该命令集合实现多次undo()和redo()操作,可以使用加法运算来模拟实现。
实验要求:
1. 提交类图;
2. 提交源代码;
// 命令接口
interface Command {
void execute();
void undo();
}
// 加法命令类
class AddCommand implements Command {
private int operand1;
private int operand2;
private int result;
public AddCommand(int operand1, int operand2) {
this.operand1 = operand1;
this.operand2 = operand2;
}
@Override
public void execute() {
result = operand1 + operand2;
System.out.println(operand1 + " + " + operand2 + " = " + result);
}
@Override
public void undo() {
System.out.println("撤销操作:" + operand1 + " + " + operand2 + ",结果恢复为:" + operand1);
}
}
import java.util.ArrayList;
// 命令集合类
class CommandList {
private ArrayList<Command> commands = new ArrayList<>();
private int currentIndex = -1;
public void addCommand(Command command) {
// 如果当前索引小于命令列表大小减1,说明有命令被撤销过,需要移除撤销后的命令
while (currentIndex < commands.size() - 1) {
commands.remove(commands.size() - 1);
}
commands.add(command);
currentIndex++;
}
public void undo() {
if (currentIndex >= 0) {
Command command = commands.get(currentIndex);
command.undo();
currentIndex--;
}
}
public void redo() {
if (currentIndex < commands.size() - 1) {
currentIndex++;
Command command = commands.get(currentIndex);
command.execute();
}
}
}
public class Main {
public static void main(String[] args) {
CommandList commandList = new CommandList();
// 执行加法命令
commandList.addCommand(new AddCommand(5, 3));
commandList.addCommand(new AddCommand(10, 2));
commandList.addCommand(new AddCommand(7, 4));
// 撤销操作
commandList.undo();
commandList.undo();
// 重复操作
commandList.redo();
commandList.redo();
}
}
3. 注意编程规范。

浙公网安备 33010602011771号