命令模式:你的系统设计一个命令行界面,用户可输入命令来执行某项功能。通过命令来执行该命令执行具体要做的事情,这个可以应对系统不因功能的添加而修改,又可灵活加入命令和功能。
以命令的方式,解耦调用者与功能的具体实现者,降低系统耦合度,提供了灵活性。如:Servlet Controller 线程池。
image.png接下来我们举个应用场景:点奶茶,通过客户点单选择不同的奶茶执行,相应的流程。

示例代码

  1. /**
  2. * 统一抽象出来的命令操作
  3. */
  4. public interface Command {
  5. public void build();//生产奶茶
  6. }
  7. /**
  8. * 命令之-烧仙草
  9. */
  10. public class ShaoxiancaoMilk implements Command {
  11. public void build() {
  12. System.out.println("制作烧仙草");
  13. }
  14. }
  15. /**
  16. * 命令之-木瓜
  17. */
  18. public class PawpawMilk implements Command {
  19. @Override
  20. public void build() {
  21. System.out.println("制作木瓜奶茶");
  22. }
  23. }
  24. /**
  25. * 命令之-原味
  26. */
  27. public class TasteMilk implements Command {
  28. @Override
  29. public void build() {
  30. System.out.println("开始制作原味奶茶");
  31. }
  32. }
  33. /**
  34. * 服务生招待客人
  35. */
  36. public class Waitress {
  37. private Map<String, Command> commands = new HashMap<>();
  38. public void register(String cmd, Command run) {
  39. commands.put(cmd, run);
  40. }
  41. /**
  42. * 客人点单
  43. */
  44. public void receiver(String command) {
  45. System.out.println("您选择了:"+command);
  46. Command cmd = commands.get(command);
  47. if(cmd == null) {
  48. System.out.println("没有这样的品种");
  49. }else {
  50. cmd.build();
  51. }
  52. }
  53. public void showMenu() {
  54. System.out.println("老板你好,本有以下奶茶:");
  55. commands.keySet().forEach((item)->{
  56. System.out.println("\t"+item);
  57. });
  58. }
  59. }

测试代码:

  1. public static void main(String[] args) {
  2. Waitress waiter = new Waitress();
  3. waiter.register("烧仙草", new ShaoxiancaoMilk());
  4. waiter.register("原味奶茶", new TasteMilk());
  5. waiter.register("木瓜奶茶", new PawpawMilk());
  6. waiter.showMenu();
  7. Scanner scanner = new Scanner(System.in);
  8. System.out.println("请选择:");
  9. // 发送内容
  10. String command = scanner.nextLine();
  11. waiter.receiver(command);
  12. scanner.close();
  13. }
  14. --控制台
  15. 老板你好,本有以下奶茶:
  16. 木瓜奶茶
  17. 烧仙草
  18. 原味奶茶
  19. 请选择:
  20. 木瓜奶茶 (控制台输入的)
  21. 您选择了:木瓜奶茶
  22. 制作木瓜奶茶

image.png