【设计模式】命令模式--封装调用

知识共享许可协议 版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons

前言

     命令模式是行为型模式之一,特点是将“请求”封装成对象,以便使用不同的请求,队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。

餐厅命令模式

 角色

     顾客、女招待、订单、快餐厨师。

 职责

  1.    顾客发出订单请求
  2.    订单封装了准备餐点的请求
  3.    女招待工作是接收订单takeOrder(order),调用订单的orderUp()方法
  4.    快餐厨师实现创建餐点的所有方法。

                                                   

命令模式

  1.实现过程

                                

2.命令模式类图

                                     

二、智能家电需求

1.角色

角色:遥控器、家用电器(电灯)、动作(打开或关闭)

通过遥控器,控制电灯的动作。

2.要求

电灯和遥控器之间要解耦,不同厂商提供的电器,只需要一个遥控器就可以,之后可以动态添加电器。

三、遥控器打开或关闭灯代码

1.Light对象

public class Light {
    private String name;
    public Light(String name){
        this.name=name;
    }
    public void on(){
        System.out.println(this.name+"的灯打开了");
    }
    public void off(){
        System.out.println(this.name+"的灯关闭了");

    }
}

2.Command接口

命令接口,只有一个方法

public interface Command {
     void execute();
}

3.两个实现Command接口的命令类

这是两个命令,需要实现command接口,构造器传入的参数电灯Light是接收者,负责接受请求。

LightOnCommand类 打开灯的命令类

public class LightOnCommand implements Command {

    Light light;
    public LightOnCommand(Light light){
        this.light=light;
    }

    @Override
    public void execute() {
        light.on();
    }
}

  LightOffCommand类 关闭灯的命令类

public class LightOffCommand implements Command {

    Light light;
    public LightOffCommand(Light light){
        this.light=light;
    }

    @Override
    public void execute() {
        light.off();
    }
}

 4.SimpleRemoteControl 遥控器类

   它只有一个按钮和对应的插槽,可以控制一个装置,Commadn slot 是一个插槽持有的命令,这个命令控制着一个装置。 

public class SimpleRemoteControl {
    Command slot;
    public  SimpleRemoteControl(){}
    public  void setCommand(Command command){
        slot=command;
    }
    public void buttonWasPressed(){
        slot.execute();
    }
}

 5.测试类

public class RemoteControlTest {
    public static void main(String[] args){
        SimpleRemoteControl remote=new SimpleRemoteControl();
        Light light=new Light("客厅");
        LightOnCommand lightON=new LightOnCommand(light);
        LightOffCommand lightOff=new LightOffCommand(light);
        remote.setCommand(lightON);
        remote.buttonWasPressed();

        remote.setCommand(lightOff);
        remote.buttonWasPressed();
    }
}

 运行结果图

                                                                                      感谢您的访问!

猜你喜欢

转载自blog.csdn.net/m18633778874/article/details/94862992