命令模式

命令模式(Command),将一个请求封装成一个对象,从而使你可用不同的请求对客户进行参数化;
对请求排队或记录请求日志,以及支持可撤销的操作。

 

 

命令模式的优点:
1.它能比较容易的设计一个命令队列
2.在需要的情况下,可以较容易的把命令记录在日志
3.允许接受请求的一方决定是否要否决请求
4.可以轻易的实现请求的撤销与重做
5.由于加入新的具体命令类不影响其它类,因此增加新的具体命令类很容易
最关键的优点是,命令模式把请求一个操作的对象与知道怎么执行一个操作的对象分割开

示例代码:

1 public abstract class Command {
2     protected Receiver receiver;
3 
4     public Command(Receiver receiver) {
5         this.receiver = receiver;
6     }
7      public abstract void execute();
8     
9 }
Command
 1 public class ConcreteCommand extends Command {
 2 
 3     public ConcreteCommand(Receiver receiver) {
 4         super(receiver);
 5     }
 6 
 7     @Override
 8     public void execute() {
 9         receiver.action();
10 
11     }
12 
13 }
ConcreteCommand
 1 public class Invoker {
 2     private Command command;
 3 
 4     public Command getCommand() {
 5         return command;
 6     }
 7 
 8     public void setCommand(Command command) {
 9         this.command = command;
10     }
11     
12     public void executeCommand(){
13         command.execute();
14     }
15 }
Invoker
1 public class Receiver {
2     
3     public void action(){
4         System.out.println("执行请求。。");
5     }
6 }
Receiver
 1 public class CommandTest {
 2     public static void main(String[] args) {
 3         Receiver re = new Receiver();
 4         Command com = new ConcreteCommand(re); 
 5         Invoker in = new Invoker();
 6         
 7         in.setCommand(com);
 8         in.executeCommand();
 9     }
10 }
11 
12 //打印
13 //执行请求。。
test

 

posted @ 2020-07-28 16:17  就是你baby  阅读(251)  评论(0编辑  收藏  举报