【问题标题】:Shifting history in command-pattern with undo/redo?使用撤消/重做的命令模式转换历史?
【发布时间】:2016-11-18 12:53:24
【问题描述】:

我遇到了关于具有撤消/重做功能的命令模式的问题。简单的问题是,当我的历史记录已满时,我想从历史记录中删除最近最少使用的命令,并在执行时添加新命令。

我从教授那里得到了这个代码 sn-p:

public class CommandHistory implements CommandInterface{

private static final int MAX_COMMANDS = 2;

private Command[] history = new Command[MAX_COMMANDS];


private int current = -1;

@Override
public void execute(Command command) {
    current++;

    if (current == MAX_COMMANDS){                     // if full, then shift
        for (int i = 0; i < MAX_COMMANDS - 1; i++){
            history[i] = history[i+1];
        }

    }
    history[current] = command;
    history[current].execute();
}

确实怀疑 if 子句 是不正确的,因为当前命令索引仍然是 2,并且只有索引 0 处的命令被转移到 1。但他说这是要走的路。我错过了什么?

【问题讨论】:

    标签: java arrays history undo command-pattern


    【解决方案1】:

    循环本身很好,但是有两个问题:

    1. 你说得很对,当current == MAX_COMMANDS 为真并且你执行循环时,current 不正确,需要调整。

    2. 从维护的角度来看,current == MAX_COMMANDS 是错误的比较,应该是current == history.length。 (否则,很容易将 history 的初始化更改为使用 MAX_COMMANDS 以外的其他内容,但忘记更改每个检查,如 current == MAX_COMMANDS。)

    我会检查current 之前增加它,并且只有在你不向下移动内容时才增加它:

    public void execute(Command command) {
    
        if (current == history.length - 1){                     // if full, then shift
            for (int i = 0; i < history.length - 1; i++) {
                history[i] = history[i+1];
            }
        } else {
            current++;
        }
        history[current] = command;
        history[current].execute();
    }
    

    【讨论】:

    • 感谢您的快速回答。这听起来确实更合理,但我不必重置当前计数器吗?如果我们说我们通过 current = 2 的循环,那么下一个循环不会像以前一样总是导致 history[0] = history[1] 和 history[1] = history[2],所以索引 history[0]从未使用过?
    • @Blixxen:不。保存第一个命令时,current-1,测试为假,您执行current++ 使其变为0 并将命令存储在那里。保存下一个时,current0,测试为假,您执行current++ 使其成为1,然后将命令存储在那里。保存下一个时,current1,因此测试为 true,您在循环中执行 history[0] = history[1](仅运行一次),然后将新命令存储在 current ,仍然是1
    • 我的错。谢谢你,先生!
    猜你喜欢
    • 1970-01-01
    • 2011-03-16
    • 2015-06-22
    • 2011-06-14
    • 1970-01-01
    • 2023-03-10
    • 2012-05-20
    • 2013-01-17
    • 1970-01-01
    相关资源
    最近更新 更多