2016-07-15 32 views
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。但他說這是要走的路。我錯過了什麼?

回答

0

循環本身是好的,但兩個問題:

  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(); 
} 
+0

謝謝你的快速回答。這聽起來更合理,但是我不必重置電流計數器嗎?如果我們說我們經歷了current = 2的循環,那麼下一個循環不會像以前一樣導致history [0] = history [1]和history [1] = history [2],所以索引歷史[0]從未使用? – Blixxen

+0

@Blixxen:沒有。當保存第一個命令時,'current'是'-1',測試是錯誤的,並且你做'current ++'使它成爲'0'並且在那裏存儲命令。當保存下一個時,'current'是'0',測試是錯誤的,你使用'current ++'使它成爲'1'並且你在那裏存儲命令。當保存下一個時,'current'爲'1',所以測試爲** true **,並且您在循環(它只運行一次)中執行'history [0] = history [1]',然後存儲新的命令在'當前',仍然是'1'。 –

+1

我的不好。謝謝你,先生! – Blixxen

相關問題