打字猴:1.700463491e+09
1700463491
1700463492 }
1700463493
1700463494 }
1700463495
1700463496 定义了两个具体的命令类,读者可以在实际应用中扩展该命令类。在每个命令类中,通过构造函数定义了该命令是针对哪一个接收者发出的,定义一个命令接收的主体。调用者非常简单,仅实现命令的传递,如代码清单15-17所示。
1700463497
1700463498 代码清单15-17 调用者Invoker类
1700463499
1700463500 public class Invoker{
1700463501
1700463502 private Command command;
1700463503
1700463504 //受气包,接受命令
1700463505
1700463506 public void setCommand(Command_command){
1700463507
1700463508 this.command=_command;
1700463509
1700463510 }
1700463511
1700463512 //执行命令
1700463513
1700463514 public void action(){
1700463515
1700463516 this.command.execute();
1700463517
1700463518 }
1700463519
1700463520 }
1700463521
1700463522 调用者就像是一个受气包,不管什么命令,都要接收、执行!那我们来看高层模块如何调用命令模式,如代码清单15-18所示。
1700463523
1700463524 代码清单15-18 场景类
1700463525
1700463526 public class Client{
1700463527
1700463528 public static void main(String[]args){
1700463529
1700463530 //首先声明调用者Invoker
1700463531
1700463532 Invoker invoker=new Invoker();
1700463533
1700463534 //定义接收者
1700463535
1700463536 Receiver receiver=new ConcreteReciver1();
1700463537
1700463538 //定义一个发送给接收者的命令
1700463539
1700463540 Command command=new ConcreteCommand1(receiver);
[ 上一页 ]  [ :1.700463491e+09 ]  [ 下一页 ]