2024.11.15
设计模式实验十六
软件设计 石家庄铁道大学信息学院
实验16:命令模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解命令模式的动机,掌握该模式的结构;
2、能够利用命令模式解决实际问题。
[实验任务一]:多次撤销和重复的命令模式
某系统需要提供一个命令集合(注:可以使用链表,栈等集合对象实现),用于存储一系列命令对象,并通过该命令集合实现多次undo()和redo()操作,可以使用加法运算来模拟实现。
实验要求:
1. 提交类图;
2. 提交源代码;
import java.util.Stack;
// 抽象命令类
abstract class AbstractCommand {
public abstract int execute(int value); // 执行操作
public abstract int undo(); // 撤销操作
public abstract int redo(); // 重做操作
}
// 加法操作类
class Adder {
private int num = 0;
public int add(int value) {
num += value;
return num;
}
public int getResult() {
return num;
}
}
// 具体命令类:加法命令
class AddCommand extends AbstractCommand {
private Adder adder;
private Stack<Integer> undoStack = new Stack<>();
private Stack<Integer> redoStack = new Stack<>();
public AddCommand(Adder adder) {
this.adder = adder;
}
@Override
public int execute(int value) {
int result = adder.add(value);
undoStack.push(value); // 将操作值存入撤销栈
redoStack.clear(); // 清空重做栈
return result;
}
@Override
public int undo() {
if (!undoStack.isEmpty()) {
int value = undoStack.pop();
redoStack.push(value); // 将操作值存入重做栈
return adder.add(-value); // 撤销操作
}
System.out.println("无操作可以撤销!");
return adder.getResult();
}
@Override
public int redo() {
if (!redoStack.isEmpty()) {
int value = redoStack.pop();
undoStack.push(value); // 将操作值重新放回撤销栈
return adder.add(value); // 重做操作
}
System.out.println("无操作可以重做!");
return adder.getResult();
}
}
// 客户端类:计算器表单
class CalculatorForm {
private AbstractCommand command;
public void setCommand(AbstractCommand command) {
this.command = command;
}
public void compute(int value) {
int result = command.execute(value);
System.out.println("当前结果:" + result);
}
public void undo() {
int result = command.undo();
System.out.println("撤销后结果:" + result);
}
public void redo() {
int result = command.redo();
System.out.println("重做后结果:" + result);
}
}
// 测试类
public class CommandPatternDemo {
public static void main(String[] args) {
Adder adder = new Adder();
AddCommand addCommand = new AddCommand(adder);
CalculatorForm calculator = new CalculatorForm();
calculator.setCommand(addCommand);
calculator.compute(10); // 加10
calculator.compute(20); // 加20
calculator.undo(); // 撤销20
calculator.redo(); // 重做20
calculator.undo(); // 再次撤销20
calculator.undo(); // 撤销10
calculator.redo(); // 重做10
}
}
3. 注意编程规范。