标签:
将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化,对请求排队或者记录请求日志,以及支持可撤销的操作。
package com.hml.command; public abstract class Command { protected Receiver receiver; public Command(Receiver receiver) { this.receiver = receiver; } public abstract void excute(); }
package com.hml.command; public class ConcretaeCommand extends Command { public ConcretaeCommand(Receiver receiver) { super(receiver); } @Override public void excute() { receiver.action(); } }
package com.hml.command; /** * 该类知道如何去处理命令 ,不同的命令可以有不同的Receiver */ public class Receiver { public void action() { System.out.println("Receiver"); } }
package com.hml.command; public class Invoker { private Command command; public Command getCommand() { return command; } public void setCommand(Command command) { this.command = command; } public void excute() { command.excute(); } }
package com.hml.command; public class Test { public static void main(String[] args) { Receiver r = new Receiver(); Command command = new ConcretaeCommand(r); Invoker i = new Invoker(); i.setCommand(command); i.excute(); } }
命令模式的优点:
1、比较容易设计命令队列
2、可以容易的将命令记录日志
3、接收请求方可决定是否接收请求
4、可以容易的实现请求撤销和重做
5、增加新的命令不影响其他的类,因此增加新的命令类很容易
标签:
原文地址:http://www.cnblogs.com/heml/p/4652522.html