2011年4月18日 星期一

GoF Behavioral - Command Pattern


  • Intent


to encapsulate a request as an object, thereby letting you parameterize clients with different requests,queue or log requests, and support rollback types of operations.


Command pattern is also known as Action or Transaction




  • Benefits




  1. 區隔開呼叫程序方法的物件實體以及實際提供物件方法的物件實體,也就是說將動作的要求者以及動作的執行者之間鬆綁

  2. 簡化了新增新命令物件的作法,因為已經存在的命令物件不需要被變動到,也就是說 我把每個特定的動作都封裝成物件來處理,每個特殊的動作都有其對應的物件,所以不會對既有的物件產生影響。




  • 適用情境




  1. 對每一個client動作發生時,都需要將其視為物件作為傳遞訊息使用

  2. 傳遞訊息時,從發出訊息到等待柱列、執行是在不同的時間點發生

  3. 需要有rollback機制以及logging機制




  • 常用API




  1. MessageBeans invoke business logic based on content of messages dispatched to them.

  2. Servlets/JSPs are invoked corresponding to the type of HTTP request that is recevied by the web container.




  • Story


想像一下,假設有個遙控器可以控制電腦開關,所以我們設計了個on off method,但有一天想要做一個萬用遙控器時,希望可以處理10種不同電器,那是不是真的要在遙控器上放10個按鈕?




  • Class Diagram




[caption id="attachment_235" align="alignnone" width="448" caption="CommandPattern"]CommandPattern[/caption]


  • Sample Code



package commandpattern;

interface Command {
public void execute();
}

class Light {
public void on() {
System.out.println("light is on! ");
}

public void off() {
System.out.println("light is off!");
}
}

class LightOnCommand implements Command {
Light light;

@Override
public void execute() {
// TODO Auto-generated method stub
light.on();
}

public LightOnCommand(Light light) {
this.light = light;
}

}

class SimpleRemoteControl {
Command slot;

public SimpleRemoteControl(){}
public SimpleRemoteControl(Command com) {
this.slot = com;
}

public void setCommand(Command com) {
this.slot = com;
}

public void buttonWasPressed() {
slot.execute();
}
}

public class CommandPattern {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

SimpleRemoteControl remote = new SimpleRemoteControl();
Light light = new Light();
LightOnCommand lightOn = new LightOnCommand(light);
remote.setCommand(lightOn);
remote.buttonWasPressed();
}

}

沒有留言: