2
我在使用撤消/重做功能命令模式時遇到問題。簡單的問題是,當我的歷史記錄已滿時,我想從歷史記錄中刪除最近最少使用的命令,並在執行時添加新命令。用撤銷/重做在命令模式中移動歷史記錄?
我從我的教授這樣的代碼片段:
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();
}
在真懷疑如果從句是不正確的,因爲當前的命令指數保持2和索引0只命令移位至1。但他說這是要走的路。我錯過了什麼?
謝謝你的快速回答。這聽起來更合理,但是我不必重置電流計數器嗎?如果我們說我們經歷了current = 2的循環,那麼下一個循環不會像以前一樣導致history [0] = history [1]和history [1] = history [2],所以索引歷史[0]從未使用? – Blixxen
@Blixxen:沒有。當保存第一個命令時,'current'是'-1',測試是錯誤的,並且你做'current ++'使它成爲'0'並且在那裏存儲命令。當保存下一個時,'current'是'0',測試是錯誤的,你使用'current ++'使它成爲'1'並且你在那裏存儲命令。當保存下一個時,'current'爲'1',所以測試爲** true **,並且您在循環(它只運行一次)中執行'history [0] = history [1]',然後存儲新的命令在'當前',仍然是'1'。 –
我的不好。謝謝你,先生! – Blixxen