设计模式 -- 命令模式

228 阅读2分钟

「这是我参与11月更文挑战的第9天,活动详情查看:2021最后一次更文挑战含义: 将一个请求以命令的方式封装成一个对象,从而使命令和执行对象分离开。说白了就是将请求者和执行者解耦。

前几天华为开了一个华为全场景智慧生活新品发布会,包括智慧出行、智慧办公、运动健康、影音娱乐、智能家居这五个方面。不得不说华为已经越来越厉害了,虽然他也越来越贵了。回归正题,下面我拿智能家居这里举例子讲解命令模式好了。

通过华为全屋智能主机能够控制所有的家具

1.家电

 public class Light{
     public void on(){
         System.out.println("打开电灯");
     }
  
     public void off(){
         System.out.println("关闭电灯");
     }
 }

 public class Curtain{
     public void on(){
         System.out.println("打开窗帘");
     }
  
     public void off(){
         System.out.println("关闭窗帘");
     }
 }

 public class Television{
     public void on(){
         System.out.println("打开电视");
     }
  
     public void off(){
         System.out.println("关闭电视");
     }
 }

2.接口

 public interface Command{
     public void execute();
 }

3.具体命令

 //关闭电灯的命令
 public class CurtainOffCommond implements Command{
     private Curtain curtain ; 
     
     public CurtainOffCommond(Curtain curtain){
         this.curtain = curtain;
     }
  
     @Override
     public void execute(){
         curtain.off();
     } 
 }

 //打开电灯的命令
 public class CurtainOnCommond implements Command{
     private Curtain curtain ; 
     
     public CurtainOnCommond(Curtain curtain){
         this.curtain = curtain;
     }
  
     @Override
     public void execute(){
         curtain.on();
     }
 }

4.主机

 public class Host{
     private static final int CONTROL_SIZE = 9;
     private Command[] commands;
  
     public Host(){
         commands = new Command[CONTROL_SIZE];
         for (int i = 0; i < CONTROL_SIZE; i++){
             commands[i] = new NoCommand();
         }
     }
  
     public void setCommand(int index, Command command){
         commands[index] = command;
     }
  
     public void keyPressed(int index){
         commands[index].execute();
     }
  }

 public class NoCommand implements Command{
     @Override
     public void execute(){ 
     }
 }

5.测试

 public class Test
 {
     public static void main(String[] args){

         Light light = new Light();
         Curtain curtain = new Curtain();
         Television television = new Television();
         
         Host host = new Host();
         host.setCommand(0, new LightOnCommond(light));
         host.keyPressed(0);
     }
 }

6.全屋智能当然不能只是单一的执行,当有需求的时候,同样可以一键同步,定义一个共用的命令

 public class ShareCommand implements Command{
     private Command[] commands;
  
     public ShareCommand(Command[] commands){
         this.commands = commands;
     }
  
     @Override
     public void execute(){
         for (int i = 0; i < commands.length; i++){
             commands[i].execute();
         }
     }
 }

7.实现一起接收命令

 ShareCommand shareCommand = new ShareCommand(new Command[] { new LightOnCommond(light),
                 new CurtainOnCommond(curtain), new TelevisionOffCommond(television) });
 host.setCommand(1, shareCommand);
 host.keyPressed(1);

优点: 降低了系统耦合度。

缺点: 拥有较多的命令类,繁琐复杂。

\