行为类模式(二):命令(Command)

定义

将一个请求封装成一个对象,从而让你使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能。

UML

优点

  1. 能比较容易的设计一个命令队列
  2. 可以较容易的将命令加入日志
  3. 允许接收请求的一方是否处理请求
  4. 可以容易的实现对请求的添加和删除
  5. 加进新的具体命令类不会影响到其他的类,增加具体命令类很容易
  6. 把请求一个操作的对象与指导怎么执行一个操作对象分开(解耦)

缺点

  1. 使用命令模式可能会导致某些系统有过多的具体命令类。

应用场景

  1. 系统需要将请求调用者和请求接收者解耦,使得调用者和接收者不直接交互。
  2. 系统需要在不同的时间指定请求、将请求排队和执行请求。
  3. 系统需要支持命令的撤销(Undo)操作和恢复(Redo)操作。
  4. 系统需要将一组操作组合在一起,即支持宏命令。

示例

用命令模式模拟主机按下开机按钮后主机内部的开机流程。

Java

 1 public class Main
 2 {
 3     public static void main(String[] args)
 4     {
 5         //组装主机
 6         IMainBoard mainBoard = new GigaMainBoard();
 7         ICommand openCommand = new OpenCommand(mainBoard);
 8         Box box = new Box();
 9         box.setOpenCommand(openCommand);
10         //执行开机命令
11         box.openButtonPressed();
12     }
13 
14     /**
15      * 主板接口
16      */
17     public interface IMainBoard
18     {
19         /**
20          * 开机
21          */
22         void open();
23     }
24 
25     /**
26      * 技嘉主板
27      */
28     public static class GigaMainBoard implements IMainBoard
29     {
30         @Override
31         public void open()
32         {
33             System.out.println("技嘉主板当前正在开机");
34             System.out.println("接通电源");
35             System.out.println("设备检查");
36             System.out.println("装载系统");
37             System.out.println("机器开始运行起来");
38             System.out.println("已开机");
39         }
40     }
41 
42     /**
43      * 命令接口
44      */
45     public interface ICommand
46     {
47         /**
48          * 执行命令的操作
49          */
50         void execute();
51     }
52 
53     /**
54      * 主板开机命令
55      */
56     public static class OpenCommand implements ICommand
57     {
58         private IMainBoard mainBoard;
59         
60         public OpenCommand(IMainBoard mainBoard)
61         {
62             this.mainBoard = mainBoard;
63         }
64         
65         @Override
66         public void execute()
67         {
68             mainBoard.open();
69         }
70     }
71 
72     /**
73      * 机箱类
74      */
75     public static class Box
76     {
77         private ICommand openCommand;
78         
79         public void setOpenCommand(ICommand openCommand)
80         {
81             this.openCommand = openCommand;
82         }
83 
84         /**
85          * 按下开机按钮
86          */
87         public void openButtonPressed()
88         {
89             openCommand.execute();
90         }
91     }
92 }
View Code
原文地址:https://www.cnblogs.com/hammerc/p/4743799.html