Client:创建具体的命令对象,并且设置命令对象的接收者。注意这个不是我们常规意义上的客户端,而是在组装命令对象和接收者,或许,把这个Client称为装配者会更好理解,因为真正使用命令的客户端是从Invoker来触发执行。
/** * */package com.model.command;//命令接口public interface Command {public void execute();public void undo();}
/** * */package com.model.command;//具体执行者public class EditTextCommand implements Command {private TxtObject txt;public EditTextCommand(TxtObject txt){this.txt = txt;}/* (non-Javadoc) * @see com.model.command.Command#execute() */@Overridepublic void execute() {txt.copy();}/* (non-Javadoc) * @see com.model.command.Command#undo() */@Overridepublic void undo() {txt.undo();}}
/** * */package com.model.command;//请求者public class TxtObject {public void copy(){System.out.println("This is copy function");}public void undo(){System.out.println("This is undo function");}}
/** * */package com.model.command;import java.util.ArrayList;import java.util.List;//命令接受者public class CommandReceiver {//private List<Command> executeList;public CommandReceiver(){executeList = new ArrayList<Command>();}public void setExecuteList(Command command){executeList.add(command);}public void copy(){executeList.get(executeList.size()-1).execute();}public void undo(){executeList.get(executeList.size()-1).undo();executeList.remove(executeList.get(executeList.size()-1));}}
package com.model.command;//发送请求客户端public class Client {public static void main(String[] args){CommandReceiver comm = new CommandReceiver();comm.setExecuteList(new EditTextCommand(new TxtObject()));comm.copy();comm.setExecuteList(new EditTextCommand(new TxtObject()));comm.copy();comm.undo();comm.undo();}}
总结:命令模式是一个很优美的设计模式、但他和其他设计模式一样不完美、命令模式很好的将请求者和执行者进行了解耦、支持了事物的操作等一系列问题,解决了很多问题,在struts中被广泛利用,这一点也证明了他是非常成功的一个设计模式。