24.11.21

[实验任务一]:多次撤销和重复的命令模式
某系统需要提供一个命令集合(注:可以使用链表,栈等集合对象实现),用于存储一系列命令对象,并通过该命令集合实现多次undo()和redo()操作,可以使用加法运算来模拟实现。
实验要求:

  1. 提交类图;
    image

  2. 提交源代码;
    package org.test.ruanjiansheji.minglingmoshi;

import java.util.Stack;

// 命令接口
interface Command {
void execute();
void undo();
}

// 加法命令类
class AddCommand implements Command {
private Calculator calculator;
private int operand;

public AddCommand(Calculator calculator, int operand) {
    this.calculator = calculator;
    this.operand = operand;
}

@Override
public void execute() {
    calculator.add(operand);
}

@Override
public void undo() {
    calculator.subtract(operand);  // 撤销加法操作即执行减法
}

}

// 计算器类
class Calculator {
private int value = 0;

public void add(int operand) {
    value += operand;
    System.out.println("加法操作: 当前值 = " + value);
}

public void subtract(int operand) {
    value -= operand;
    System.out.println("减法操作: 当前值 = " + value);
}

public int getValue() {
    return value;
}

}

// 命令调用者类
class CommandInvoker {
private Stack commandHistory = new Stack<>();
private Stack redoHistory = new Stack<>();

// 执行命令
public void executeCommand(Command command) {
    command.execute();
    commandHistory.push(command);
    redoHistory.clear();  // 清空重做历史
}

// 撤销操作
public void undo() {
    if (!commandHistory.isEmpty()) {
        Command command = commandHistory.pop();
        command.undo();
        redoHistory.push(command);  // 将撤销的命令推入重做历史
    } else {
        System.out.println("没有命令可以撤销");
    }
}

// 重做操作
public void redo() {
    if (!redoHistory.isEmpty()) {
        Command command = redoHistory.pop();
        command.execute();
        commandHistory.push(command);  // 将重做的命令推入历史
    } else {
        System.out.println("没有命令可以重做");
    }
}

}

// 客户端类
public class Client {
public static void main(String[] args) {
Calculator calculator = new Calculator();
CommandInvoker invoker = new CommandInvoker();

    // 创建一些加法命令
    Command add10 = new AddCommand(calculator, 10);
    Command add20 = new AddCommand(calculator, 20);
    Command add30 = new AddCommand(calculator, 30);

    // 执行命令
    invoker.executeCommand(add10);  // 执行加10
    invoker.executeCommand(add20);  // 执行加20
    invoker.executeCommand(add30);  // 执行加30

    System.out.println("当前计算结果: " + calculator.getValue());

    // 执行撤销操作
    invoker.undo();  // 撤销加30
    invoker.undo();  // 撤销加20

    System.out.println("当前计算结果: " + calculator.getValue());

    // 执行重做操作
    invoker.redo();  // 重做加20
    invoker.redo();  // 重做加30

    System.out.println("当前计算结果: " + calculator.getValue());
}

}

  1. 注意编程规范。
posted @ 2024-11-21 20:20  起名字真难_qmz  阅读(8)  评论(0)    收藏  举报