今天完成了设计模式实验十六,以下为今日实验内容:
实验16:命令模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解命令模式的动机,掌握该模式的结构;
2、能够利用命令模式解决实际问题。
[实验任务一]:多次撤销和重复的命令模式
某系统需要提供一个命令集合(注:可以使用链表,栈等集合对象实现),用于存储一系列命令对象,并通过该命令集合实现多次undo()和redo()操作,可以使用加法运算来模拟实现。
实验要求:
1. 提交类图;
2. 提交源代码;
import java.util.Stack;
// Receiver
class Calculator {
private int state;
public int getState() {
return state;
}
public void add(int value) {
state += value;
}
public void undo() {
state = 0; // 重置状态,简化实现
}
}
// Command interface
interface Command {
void execute();
void undo();
}
// ConcreteCommand
abstract class ConcreteCommand implements Command {
protected Calculator calculator;
public ConcreteCommand(Calculator calculator) {
this.calculator = calculator;
}
}
class AddCommand extends ConcreteCommand {
private int value;
public AddCommand(Calculator calculator, int value) {
super(calculator);
this.value = value;
}
@Override
public void execute() {
calculator.add(value);
}
@Override
public void undo() {
calculator.undo(); // 简化实现,实际可能需要记录每一步的具体值
}
}
// Invoker
class CommandManager {
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);
}
}
}
// Client
public class CommandPatternExample {
public static void main(String[] args) {
Calculator calculator = new Calculator();
CommandManager commandManager = new CommandManager();
Command add5 = new AddCommand(calculator, 5);
Command add3 = new AddCommand(calculator, 3);
commandManager.storeAndExecute(add5);
System.out.println("State: " + calculator.getState()); // State: 5
commandManager.storeAndExecute(add3);
System.out.println("State: " + calculator.getState()); // State: 8
commandManager.undo();
System.out.println("State: " + calculator.getState()); // State: 5
commandManager.undo();
System.out.println("State: " + calculator.getState()); // State: 0
commandManager.redo();
System.out.println("State: " + calculator.getState()); // State: 5
}
}
3. 注意编程规范。
标签:11.18,日报,calculator,undo,public,State,command,void From: https://www.cnblogs.com/lijianlongCode13/p/18571854