今天完成了設計模式實驗十六,以下為今日實驗內容:
實驗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. 注意程式設計規範。