使用 undo/redo 在命令模式中移动历史记录?
Shifting history in command-pattern with undo/redo?
我在使用 undo/redo 函数的命令模式方面遇到问题。简单的问题是,当我的历史记录已满时,我想从历史记录中删除最近最少使用的命令并在执行时添加新命令。
我从我的教授那里得到了这段代码片段:
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-clause 是不正确的,因为当前命令索引仍然是 2,只有索引 0 处的命令被转移到 1。但他说这是方式去。我错过了什么?
循环本身没问题,但有两个问题:
你说得很对,当 current == MAX_COMMANDS
为真并且你执行循环时,current
不正确,需要调整。
从维护的角度来说,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();
}
我在使用 undo/redo 函数的命令模式方面遇到问题。简单的问题是,当我的历史记录已满时,我想从历史记录中删除最近最少使用的命令并在执行时添加新命令。
我从我的教授那里得到了这段代码片段:
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-clause 是不正确的,因为当前命令索引仍然是 2,只有索引 0 处的命令被转移到 1。但他说这是方式去。我错过了什么?
循环本身没问题,但有两个问题:
你说得很对,当
current == MAX_COMMANDS
为真并且你执行循环时,current
不正确,需要调整。从维护的角度来说,
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();
}