命令模式

命令模式共有4个角色: Command, ConcurrentCommand, Reciever, Invoker

Command : 抽象命令类, 定义了Reciver成员和抽象方法executeCommand()用于执行命令

ConcurrentCommand : 具体实现命令类, 继承自Command类并实现了抽象方法executeCommand()

Reciver : 实际命令执行者, executeCommand()所产生的行为由Reciever实现

Invoker : 定义了Command成员,是Command的调用者

命令模式的优点是命令记录/撤销功能,可以批次执行命令,并且命令的产生与执行解耦,生成新的命令不需要修改源代码

 1 package command;
 2 
 3 public abstract class Command {
 4     protected Reciever reciever;
 5     
 6     protected Command(Reciever reciever) {
 7         this.reciever = reciever;
 8     }
 9     
10     public abstract void executeCommand();
11 }
12 
13 package command;
14 
15 public class ConcurrentCommand1 extends Command {
16     protected ConcurrentCommand1(Reciever reciever) {
17         super(reciever);
18     }
19 
20     @Override
21     public void executeCommand() {    // 如果需要撤销命令,则在此处插入判断条件,达成条件是撤销命令执行 22         reciever.action();
23         System.out.println("command1 executed");
24     }
25 }
26 
27 package command;
28 
29 public class ConcurrentCommand2 extends Command {
30     protected ConcurrentCommand2(Reciever reciever) {
31         super(reciever);
32     }
33 
34     @Override
35     public void executeCommand() {
36         reciever.action();
37         System.out.println("command2 executed");
38     }
39 }
40 
41 package command;
42 
43 public class Reciever {
44     private String name;
45     
46     public Reciever(String name) {
47         this.name = name;
48     }
49     
50     public void action() {
51         System.out.println("I'm " + name + ". Let me do it!");
52     }
53 }
54 
55 package command;
56 
57 public class Invoker {
58     public Command command;  // 如果需要批量执行命令,则在此处将command变为command数组,最后在使用for执行命令 59     
60     public void setCommand(Command command) {
61         this.command = command;
62     }
63     
64     public void executeCommand() {
65         command.executeCommand();
66     }
67 }
68 
69 package command;
70 
71 public class Test {
72     public static void main(String[] args) {
73         Reciever reciever = new Reciever("Jack");
74         Command command1 = new ConcurrentCommand1(reciever);
75         Command command2 = new ConcurrentCommand2(reciever);
76         Invoker invoker = new Invoker();
77         invoker.setCommand(command1);
78         invoker.executeCommand();
79         invoker.setCommand(command2);
80         invoker.executeCommand();
81     }
82 }
83 
84 // ...

程序输出

I'm Jack. Let me do it!
command1 executed
I'm Jack. Let me do it!
command2 executed

 

你可能感兴趣的:(命令模式)