14、COMMAND—俺有一個MM家里管得特別嚴(yán),沒法見面,只好借助于她弟弟在我們倆之間傳送信息,她對我有什么指示,就寫一張紙條讓她弟弟帶給我。
這不,她弟弟又傳送過來一個COMMAND,為了感謝他,我請他吃了碗雜醬面,哪知道他說:"我同時給我姐姐三個男朋友送COMMAND,就數(shù)你最小氣,才請我吃面。",:-(
命令模式:命令模式把一個請求或者操作封裝到一個對象中。命令模式把發(fā)出命令的責(zé)任和執(zhí)行命令的責(zé)任分割開,委派給不同的對象。
命令模式允許請求的一方和發(fā)送的一方獨立開來,使得請求的一方不必知道接收請求的一方的接口,更不必知道請求是怎么被接收,以及操作是否執(zhí)行,
何時被執(zhí)行以及是怎么被執(zhí)行的。系統(tǒng)支持命令的撤消。
典型的Command模式需要有一個接口.接口中有一個統(tǒng)一的方法,這就是"將命令/請求封裝為對象":
public interface Command {
public abstract void execute ( );
}
《Java與模式》一書中的例子如下:
/**
* 客戶端(Client)代碼
*/
public class Client {
public static void main(String[] args) {
Receiver receiver = new Receiver();
Command command = new ConcreteCommand(receiver);
Invoker invoker = new Invoker(command);
invoker.action();
}
}
/**
* 請求者(Invoker)角色代碼
*/
public class Invoker {
private Command command;
public Invoker(Command command) {
this.command = command;
}
public void action() {
command.execute();
}
}
/**
* 接收者(Receiver)角色代碼
*/
public class Receiver {
public Receiver() {
//write code here
}
public void action() {
System.out.println(""Action has been taken);
}
}
/**
* 抽象命令角色由Command接口扮演
*/
public class Command {
void execute();
}
/**
* 具體命令類
*/
public class ConcreteCommand implements Command {
private Receiver receiver;
public ConcreteCommand(Receiver receiver) {
this.receiver = receiver;
}
public void execute() {
receiver.action();
}
}
再用某公司寫的Command模式,簡化代碼寫個大概樣子:
/**
* 客戶端(Client)代碼
*/
public class Client {
public static void main(String[] args) {
String receiverName = "xAO";
String methodName = "methodA";
//receiverName這里用Spring的依賴注入來創(chuàng)建Receiver對象
Command command = new ConcreteCommand(receiverName);
command.getParameters.put("method", methodName); //實際代碼做了封裝,并不是這樣直接寫的。這里簡化一下
command.getParameters.put("param1", "param1"); //傳遞參數(shù)
command.getParameters.put("param2", "param2");
Result result = getNewInvoker.execute(command); //創(chuàng)建Invoker對象,并調(diào)用receiver執(zhí)行最終的方法
}
}
/**
* 請求者(Invoker)角色代碼
*/
public class Invoker {
private Command command;
public Invoker(Command command) {
this.command = command;
}
public void action() {
command.execute();
}
private BeanFactoryService beanFactory;
public Result execute(Command command) {
ApplicationObject ao = beanFactory.getBean(command.getName(), ApplicationObject.class, new XXProcessor(command));
return ao.execute(); //這里就是接收者Receiver來執(zhí)行具體方法: xAO.methodA();
}
}
/**
* 抽象命令角色由Command接口扮演
*/
public class Command {
//...
//沒有execute()方法
}
/**
* 具體命令類
*/
public class ConcreteCommand implements Command {
//也沒有execute()方法
//...
}
posted on 2008-01-24 16:45
EvanLiu 閱讀(5535)
評論(0) 編輯 收藏 所屬分類:
設(shè)計模式