命令模式:
其实我们已经用了不知道多少次这个模式了,我们在使用struts webwork的时候,其地层就采用的命令模式进行资源分发的。
UML图:
下班了 ,下周再说
上图描述,角色:调用者,命令,接受者,客户端。
代码示例:调用者
1、
public class Invoker {
Command command;
public void setCommand(Command command) {
this.command = command;
}
public Invoker() {
}
public void invoker{
command.execute();
}
}
二:
public interface Command {
public void execute();
public void undo();
}
三:
public class ConCommand implements Command{
Receiver receiver;
public ConCommand() {
// TODO Auto-generated constructor stub
}
public ConCommand(Receiver receiver){
this.receiver = receiver;
}
@Override
public void execute() {
receiver.action();
}
@Override
public void undo() {
// TODO Auto-generated method stub
}
}
四:
public class Receiver {
public void action() {
.......................................;
}
}
五:
public class Client
{
Receiver rceiver = new Receiver();
Command command = new ConcreteCommand(rceiver);
Invoker invoker = new Invoker();
/** *//** Creates a new instance of CommandPattern */
public Client()
{
}//end CommandPattern
public void showCommandPattern()
{
invoker.setCommand(command);
invoker.invoker();
}//end showCommandPattern()
public static void main(String[] args)
{
System.out.println("----------------------");
System.out.println("The Command Pattern!");
CommandPattern cp = new CommandPattern();
cp.showCommandPattern();
System.out.println("----------------------");
}//end main(...)
}//end class CommandPattern
这个就是我们说的命令模式了,
当然它也支持undo操作,就是记录用户的上一次操作或者是一系列的操作。
要点:
- invoker和recei ver解耦;
- invoker receiver 通过command沟通
- invoker通过command的execute发出请求,间接调用receiver
- invoker介绍命令作为参数
- 支持撤消操作
- 宏命令批处理
- 也可以实现事务和日志操作