2009年8月5日 星期三

Design Pattern - Command Pattern

Command Pattern

可將請求的動作與執行的動作分開

若假設現在的需求是要提供api給user使用時, 當然api會一直增加時

假設我們, 把使用者基本資料 封裝成 member object
api object用來封裝請求的資料, user不用管如何取得資料, 只要call execute()

整個Command Pattern可以想成有下列幾個角色
Client class --> createCommandObject() //要用的人就new object
Command class --> setCommand() //設定要使用那個命令
Invoker class --> execute() --> Command class //調用者會就去執行execute
Command class --> Receiver class //執行動作


宣告一個要執行命令的接口

public interface ICommand{
public String execute();
//public String executeXML(); //也可吐xml回去
}


實現取得客戶資料的命令 --> 注意這裡是指命令, 這裡就是把某個請求封裝起來

public class CustomerCommand implements ICommand{

Customer customer;

public CustomerCommand(Customer customer){
this.customer = customer;
}

public String execute(){
customer.getDB();
String result = customer.setXML();
return result;
}
}
public class EmployeeCommand implements Icommand(){ ... }

//實作如何取得資料, 並轉成xml
public class Customer{
getDB();
setXML();
...
}
public class Employee{ ... }


上面的 CustomerCommand class 與 Customer class就是把請求與執行分開來了

再來做一個統一對外執行的介面, 以後若有增加新的api, 這class是不需修改的,
這class 是上面提到的invoker角色(調用者)


public class APIControl(){

Command command;

public APIControl(){}

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

public String doExecute(){
return command.execute();
}
}

public class DemoCallAPIP{

public static void main(String[] args){
APIControl api = new APIControl();
Customer customer = new Customer();
CustomerCommand customerCommand = new customer(customer);

api.setCommand(customerCommand); //傳入要執行的命令
String xmlResult = api.doExecute(); //就執行囉
}
}

0 意見: