目的

将命令封装成对象中,具有以下作用:

  • 使用命令来参数化其他对象
  • 将命令放入队列中进行排队
  • 将命令的操作记录到日志中
  • 支持可撤销的操作

类图

  • Command: 命令
  • Receiver: 命令接收者,也就是命令真正的执行者
  • Invoker: 通过它来调用命令
  • Client: 可以设置命令与命令的接收者

命令类图.png

实现

设计一个遥控器,可以控制电灯开关。
遥控器.jpg

  1. public interface Command{
  2. void execute();
  3. }
  4. public class LightOnCommand implements Command{
  5. Light light;
  6. public LightOnCommand(Light light){
  7. this.light = light;
  8. }
  9. @Override
  10. public void execute(){
  11. light.on();
  12. }
  13. }
  14. public class LightOffCommand implements Command{
  15. Light light;
  16. public LightOffCommand(Light light){
  17. this.light = light;
  18. }
  19. @Override
  20. public void execute(){
  21. light.off();
  22. }
  23. }
  24. public class Light{
  25. public void on(){
  26. System.out.println("Light is on!");
  27. }
  28. public void off(){
  29. System.out.println("Light is off!");
  30. }
  31. }
  32. //遥控器
  33. public class Invoker{
  34. private Command[] onCommands;
  35. private Command[] offCommands;
  36. private final int slotNum = 7;
  37. public Invoker(){
  38. this.onCommand = new Command[slotNum];
  39. this.offCommand = new Command[slotNum];
  40. }
  41. public void setOnCommand(Command command, int slot){
  42. onCommands[slot] = command;
  43. }
  44. public void setOffCommand(Command command, int slot){
  45. offCommands[slot] = command;
  46. }
  47. public void onButtonWasPushed(int slot){
  48. onCommands[slot].execute();
  49. }
  50. public void offButtonWasPushed(int slot){
  51. offCommands[slot].execute();
  52. }
  53. }
  54. public class Client{
  55. public static void main(String[] args){
  56. Invoker invoker = new Invoker();
  57. Light light = new Light();
  58. Command lightOnCommand = new LightOnCommand(light);
  59. Command lightOffCommand = new LightOffCommand(light);
  60. invoker.setOnCommand(lightOnCommand, 0);
  61. invoker.setOffCommand(lightOffCommand, 0);
  62. invoker.onButtonWasPushed(0);
  63. invoker.offButtonWasPushed(0);
  64. }
  65. }

JDK中的体现