顾名思义, 命令模式就是给不同的命令然后交给别人做就可以了。
下面我们以 项目经理 下发命令给 漂亮的 女秘书 以及 TechLead 为例来介绍。
先看看命令的接受者
public abstract class Receiver {
// 接到命令肯定需要先分析分析
public abstract void analyze();
// 分析好了就可以执行
public abstract void execute();
// 执行完了再汇报一下
public abstract void report();
}
定义两个接收者: 女秘书 + TechLead
public class Secretary extends Receiver {
@Override
public void analyze() {
System.out.println("经理去见客户,晚上的飞机, 我的联系一下航空公司");
}
@Override
public void execute() {
System.out.println("打电话订票");
}
@Override
public void report() {
System.out.println("通知经理票已经订好了,晚上8点");
}
}
public class TechLead extends Receiver {
@Override
public void analyze() {
System.out.println("分析一下新的需求");
}
@Override
public void execute() {
System.out.println("召集项目组开会讨论, 制定计划, 马上执行");
}
@Override
public void report() {
System.out.println("向项目经理汇报当前进展, everything is fine.");
}
}
再来看看Command
public abstract class Command {
protected Receiver receiver;
public Command(Receiver receiver){
this.receiver = receiver;
}
public abstract void execute();
}
定义两个具体的命令, 一个给秘书, 一个给TechLead
public class BookAirTicket extends Command {
public BookAirTicket(Receiver receiver) {
super(receiver);
}
@Override
public void execute() {
super.receiver.analyze();
super.receiver.execute();
super.receiver.report();
// 除了这三部, 可能还要调 财务系统进行报销, 等等
}
}
public class ChangeRequirement extends Command {
public ChangeRequirement(Receiver receiver) {
super(receiver);
}
@Override
public void execute() {
super.receiver.analyze();
super.receiver.execute();
super.receiver.report();
// 除了这三部, 可能还要根据当前抓状态来调整计划, 等等
}
}
最后来定义同一的Invoker
public class Invoker {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void run() {
this.command.execute();
}
}
好啦, 一切都好了, 看看客户端代码是怎样下达命令的:
public class Client {
public static void main(String[] args) {
Invoker invoker = new Invoker();
Receiver secretary = new Secretary();
Command bookAirTicket = new BookAirTicket(secretary);
invoker.setCommand(bookAirTicket);
invoker.run();
System.out.println();
Receiver techLead = new TechLead();
Command changeRequirement = new ChangeRequirement(techLead);
invoker.setCommand(changeRequirement);
invoker.run();
}
}
执行结果:
引用
经理去见客户,晚上的飞机, 我的联系一下航空公司
打电话订票
通知经理票已经订好了,晚上8点
分析一下新的需求
召集项目组开会讨论, 制定计划, 马上执行
向项目经理汇报当前进展, everything is fine.
但是有个问题:
如果我想在某个具体的Receiver中加入一些特有的方法, 比如女秘书, 你懂的。。。
public class Secretary extends Receiver {
public void specialService() {
System.out.println("秘书嘛, 还应该提供些特殊的服务,你懂得, 嘿嘿~~~");
}
}
那么在BookAirTicket类里面就只能
public class BookAirTicket extends Command {
public BookAirTicket(Receiver receiver) {
super(receiver);
}
public void execute() {
[color=red]Secretary secretary = (Secretary) super.receiver;
secretary.analyze();
secretary.execute();
secretary.report();
secretary.specialService();[/color] }
}
但这样又对Secretary有依赖了。。。怎样处理这种情况呢?