转载请声明:http://www.cnblogs.com/courtier/p/4292187.html
- 命令模式的简介:
用于“行为请求者”与“行为实现者”解耦,可实现二者之间的松耦合,以便适应变化。
- 从代码方面来理解(我:调用者 遥控器:操作者又称为虚执行者 电视机:执行者):
package command; public interface Command { //延迟开机: void delay(String str); //暂停一下: void pause(String str); //马上开始: void start(String str); }
- 操作者必须持有执行者(不然,怎么知道交给谁):
package command; public class ConcreteCommand implements Command{ //持有执行者的引用 private Receiver receiver; public ConcreteCommand(Receiver receiver) { super(); this.receiver = receiver; } @Override public void delay(String str) { // TODO Auto-generated method stub str = "延迟了30秒!" + str; receiver.delay(str); } @Override public void pause(String str) { // TODO Auto-generated method stub str = "暂停!"+str; receiver.pause(str); } @Override public void start(String str) { // TODO Auto-generated method stub receiver.start(str); } }
- 真正的执行者::
package command; public class ConcreteCommand implements Command{ //持有执行者的引用 private Receiver receiver; public ConcreteCommand(Receiver receiver) { super(); this.receiver = receiver; } @Override public void delay(String str) { // TODO Auto-generated method stub str = "延迟了30秒!" + str; receiver.delay(str); } @Override public void pause(String str) { // TODO Auto-generated method stub str = "暂停!"+str; receiver.pause(str); } @Override public void start(String str) { // TODO Auto-generated method stub receiver.start(str); } }
- Client:它并不是真正的客户,它是操作者与执行者的桥梁:
package command; //组合体,因为,只有它才知道我的参数给谁调用。如果,没有它就好像一台遥控器的红外线只能一台机器用一样. public class Client { //遥控器 private static Command command; //那台电视机 private Receiver receiver; public Client(Receiver receiver) { super(); this.receiver = receiver; } //对准哪台电视机 public void assemble() { command = new ConcreteCommand(receiver); } }
- 真正的调用者:
package command; //真正的调用者 public class Invoker { //持有命令参数 private Command command; public Invoker(Command command) { super(); this.command = command; } public void runDelay(String str) { //调用了延迟,延迟多少秒由Command来决定了 command.delay(str); } public void runPause(String str) { //调用了暂停 command.pause(str); } public void runStart(String str) { //调用了开始 command.start(str); } }
- 运行结果:
(源代码:https://github.com/aliencool/Design-Pattrn/tree/master/command)
- 结束语:
命令模式是GOF经典模式之一,应用于Runnable
时间: 2024-10-06 14:08:48