实验16:命令模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解命令模式的动机,掌握该模式的结构;
2、能够利用命令模式解决实际问题。
[实验任务一]:多次撤销和重复的命令模式
某系统需要提供一个命令集合(注:可以使用链表,栈等集合对象实现),用于存储一系列命令对象,并通过该命令集合实现多次undo()和redo()操作,可以使用加法运算来模拟实现。
实验要求:
1. 提交类图;
2. 提交源代码;
3. 注意编程规范。
1.
2.// Command interface
interface Command {
void execute();
void undo();
}
// Receiver
class Calculator {
private int result = 0;
public void add(int value) {
result += value;
}
public int getResult() {
return result;
}
}
// ConcreteCommand
class AddCommand implements Command {
private Calculator calculator;
private int value;
public AddCommand(Calculator calculator, int value) {
this.calculator = calculator;
this.value = value;
}
@Override
public void execute() {
calculator.add(value);
}
@Override
public void undo() {
calculator.add(-value);
}
}
// Invoker
class CommandManager {
private HistoryStack history = new HistoryStack();
public void executeCommand(Command command) {
command.execute();
history.push(command);
}
public void undo() {
Command command = history.pop();
command.undo();
}
public void redo() {
Command command = history.peek();
command.execute();
}
}
// HistoryStack
class HistoryStack {
private Stack<Command> stack = new Stack<>();
public void push(Command command) {
stack.push(command);
}
public Command pop() {
return stack.pop();
}
public Command peek() {
return stack.peek();
}
}
// Client
public class CommandPatternExample {
public static void main(String[] args) {
Calculator calculator = new Calculator();
CommandManager manager = new CommandManager();
Command add5 = new AddCommand(calculator, 5);
Command add10 = new AddCommand(calculator, 10);
Command add15 = new AddCommand(calculator, 15);
manager.executeCommand(add5);
manager.executeCommand(add10);
System.out.println("Result: " + calculator.getResult()); // Should print 15
manager.undo();
System.out.println("Result after undo: " + calculator.getResult()); // Should print 5
manager.redo();
System.out.println("Result after redo: " + calculator.getResult()); // Should print 15
}
}