2011-07-21 96 views
1

這裏是一個關於將輸入鍵映射到實現狀態模式的類中的動作的最佳策略的編程樣式問題。在實現狀態模式時將鍵綁定應用於狀態轉換

我處理兩類:

第一實施狀態模式,控制多狀態物理設備:

class DeviceController { 
    State _a, _b, _current; 

    // Actions that may prompt a transition from one state to another 
    public void actionA() { ... } 
    public void actionB() { ... } 
    public void actionC() { ... } 

    public State getStateA() { ... } 
    public State getStateB() { ... } 

    public void setCurrentState() { ... } 
}; 

第二個是,檢索所有的鍵盤輸入一個的KeyListener和呼叫從所述設備控制器的適當的動作,當按下輸入鍵匹配的(暫時)硬編碼綁定表:

class KeyDemo implements KeyListener { 

    DeviceController _controller; 
    ... 
    @Override 
    public void keyPressed(KeyEvent arg0) { 
     char key = Character.toUpperCase(arg0.getKeyChar()); 
     switch (key) { 
     case 'A': 
      _controller.actionA(); 
      break; 
     case 'B' : 
     ... 
    } 
    ... 
} 

是有一種最佳實踐編碼風格將鍵與控制器中的動作綁定在一起?我是否必須通過switch語句,如示例代碼中所示?在我看來,這個解決方案有點髒代碼:是不是應該消除不可否認的狀態模式,如果和切換控制結構?

謝謝你的建議。

回答

0

使用多態可以實現您的目標。我已經使用枚舉,但也許它會更適合使用接口或抽象類,然後實現每個關鍵處理器。你怎麼看?

import java.awt.event.KeyEvent; 
import java.awt.event.KeyListener; 

enum KeyProcessor { 
    A { 
     void executeAction() { 
      _controller.actionA(); 
     } 
    }, 
    B { 
     void executeAction() { 
      _controller.actionB(); 
     } 
    }; 

    private static final DeviceController _controller = new DeviceController(); 

    void executeAction() { 
     System.out.println("no action defined"); 
    } 
} 

class DeviceController { 
    State _a; 
    State _b; 
    State _current; 

    // Actions that may prompt a transition from one state to another 
    public void actionA() { 
     System.out.println("action A performed."); 

    } 

    public void actionB() { 
     System.out.println("action B performed."); 
    } 

    public void actionC() { 
    } 

    public State getStateA() { 
     return null; 
    } 

    public State getStateB() { 
     return null; 
    } 

    public void setCurrentState() { 
    } 
} // end class DeviceController 

public class KeyDemo implements KeyListener { 

    DeviceController _controller; 

    // ... 
    @Override 
    public void keyPressed(KeyEvent arg0) { 
     keyPressed(Character.toUpperCase(arg0.getKeyChar())); 
     // ... 
    } 

    public void keyPressed(char c) { 
     KeyProcessor processor = KeyProcessor.valueOf(c + ""); 
     if (processor != null) { 
     processor.executeAction(); 
    } 

    } 

    @Override 
    public void keyTyped(KeyEvent e) { 
    } 

    @Override 
    public void keyReleased(KeyEvent e) { 
    } 

    public static final void main(String[] args) { 
     KeyDemo main = new KeyDemo(); 
     main.keyPressed('A'); 
     main.keyPressed('B'); 
    } 
} // end class KeyDemo 

class State { 
}