14、COMMAND—俺有一個(gè)MM家里管得特別嚴(yán),沒法見面,只好借助于她弟弟在我們倆之間傳送信息,她對(duì)我有什么指示,就寫一張紙條讓她弟弟帶給我。
這不,她弟弟又傳送過來一個(gè)COMMAND,為了感謝他,我請(qǐng)他吃了碗雜醬面,哪知道他說:"我同時(shí)給我姐姐三個(gè)男朋友送COMMAND,就數(shù)你最小氣,才請(qǐng)我吃面。",:-(
命令模式:命令模式把一個(gè)請(qǐng)求或者操作封裝到一個(gè)對(duì)象中。命令模式把發(fā)出命令的責(zé)任和執(zhí)行命令的責(zé)任分割開,委派給不同的對(duì)象。
命令模式允許請(qǐng)求的一方和發(fā)送的一方獨(dú)立開來,使得請(qǐng)求的一方不必知道接收請(qǐng)求的一方的接口,更不必知道請(qǐng)求是怎么被接收,以及操作是否執(zhí)行,
何時(shí)被執(zhí)行以及是怎么被執(zhí)行的。系統(tǒng)支持命令的撤消。
典型的Command模式需要有一個(gè)接口.接口中有一個(gè)統(tǒng)一的方法,這就是"將命令/請(qǐng)求封裝為對(duì)象":
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();
}
}
/**
* 請(qǐng)求者(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模式,簡(jiǎn)化代碼寫個(gè)大概樣子:
/**
* 客戶端(Client)代碼
*/
public class Client {
public static void main(String[] args) {
String receiverName = "xAO";
String methodName = "methodA";
//receiverName這里用Spring的依賴注入來創(chuàng)建Receiver對(duì)象
Command command = new ConcreteCommand(receiverName);
command.getParameters.put("method", methodName); //實(shí)際代碼做了封裝,并不是這樣直接寫的。這里簡(jiǎn)化一下
command.getParameters.put("param1", "param1"); //傳遞參數(shù)
command.getParameters.put("param2", "param2");
Result result = getNewInvoker.execute(command); //創(chuàng)建Invoker對(duì)象,并調(diào)用receiver執(zhí)行最終的方法
}
}
/**
* 請(qǐng)求者(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)
評(píng)論(0) 編輯 收藏 所屬分類:
設(shè)計(jì)模式