命令模式:將請求封裝成對象,以便使用不同的請求、隊列或者日誌來參數化其它對象。 命令對象:通過在特定接收者上綁定一組動作來封裝一個請求。要達到這一點,命令對象將動作和接收者包進對象中,只暴露出一個execute()方法,這方法被調用的時候,接收者就會執行這些動作。 實現命令介面(所有的命令對象都必須 ...
命令模式:將請求封裝成對象,以便使用不同的請求、隊列或者日誌來參數化其它對象。
命令對象:通過在特定接收者上綁定一組動作來封裝一個請求。要達到這一點,命令對象將動作和接收者包進對象中,只暴露出一個execute()方法,這方法被調用的時候,接收者就會執行這些動作。
-
實現命令介面(所有的命令對象都必須實現這一介面)
1 public interface Command { 2 3 public void execute(); 4 5 }View Code
2.實現一個打開電燈的命令(繼承命令介面)
1 public class Ligth { 2 3 public void on(){ 4 5 //開燈 6 7 } 8 9 public void off(){ 10 11 //關燈 12 13 } 14 15 }View Code
1 public class LightOnCommand implements Command { 2 3 Ligth light; 4 5 public LightOnCommand(Ligth light){ 6 7 this.light=light; 8 9 } 10 11 @Override 12 13 public void execute() { 14 15 // TODO Auto-generated method stub 16 17 light.on(); 18 19 } 20 21 }View Code
3.使用命令對象
假設有一個插槽,該插槽有就只有一個命令。
1 public class SimpleRemoteControl { 2 3 Command slot; 4 5 6 7 public void setCommand(Command command) { 8 9 this.slot = command; 10 11 } 12 13 public void buttonWasPressed(){ 14 15 slot.execute(); 16 17 } 18 19 }View Code
說明:
- SimpleRemoteControl就是一個調用者,會傳入一個命令對象,可以用來發出請求
- Light就是請求的接收者
- LightOnCommand命令對象,需要將接收者傳給它
- 調用者就可以設置命令,然後執行按鈕
1 public static void main(String[] args) { 2 3 //創建一個調用者 4 5 SimpleRemoteControl remote=new SimpleRemoteControl(); 6 7 //創建一個接收者 8 9 Light light=new Light(); 10 11 //創建一個命令,將接收者傳給它 12 13 LightOnCommand lightOn=new LightOnCommand(light); 14 15 //執行調用者(1.設置命令,2.打開按鈕) 16 17 remote.setCommand(lightOn); 18 19 remote.buttonWasPressed(); 20 21 }View Code