《HeadFirst设计模式(第二版)》第六章代码——命令模式

代码文件目录:

Command
package Chapter6_CommandPattern.Command;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

public interface Command {
    public void execute();
    public void undo();//撤销该指令
}
CeilingFan
package Chapter6_CommandPattern.ElectricAppliance;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

//吊扇
public class CeilingFan {

    public static final int HIGH = 3;
    public static final int MEDIUM = 2;
    public static final int LOW = 1;
    public static final int OFF = 0;
    String location;
    int speed;

    public CeilingFan(String location){
        this.location = location;
        this.speed = OFF;
    }

    public void high(){
        this.speed = HIGH;
        System.out.println(this.location+" ceilingFan is on High");
    }

    public void medium(){
        this.speed = MEDIUM;
        System.out.println(this.location+" ceilingFan is on Medium");
    }

    public void low(){
        this.speed = LOW;
        System.out.println(this.location+" ceilingFan is on Low");
    }

    public void off(){
        this.speed = OFF;
        System.out.println(this.location+" ceilingFan is on Off");
    }

    public int getSpeed(){
        return this.speed;
    }

}
CeilingFanHighCommand
package Chapter6_CommandPattern.Command;

import Chapter6_CommandPattern.ElectricAppliance.CeilingFan;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

public class CeilingFanHighCommand implements Command{
    CeilingFan ceilingFan;
    int prevSpeed;//保存上一个挡位

    public CeilingFanHighCommand(CeilingFan ceilingFan){
        this.ceilingFan = ceilingFan;
    }

    @Override
    public void execute() {
        this.prevSpeed = this.ceilingFan.getSpeed();
        this.ceilingFan.high();
    }

    @Override
    public void undo() {
        if(this.prevSpeed==CeilingFan.HIGH){
            this.ceilingFan.high();
        }else if(this.prevSpeed == CeilingFan.MEDIUM){
            this.ceilingFan.medium();
        }else if(this.prevSpeed == CeilingFan.LOW){
            this.ceilingFan.low();
        }else if(this.prevSpeed == CeilingFan.OFF){
            this.ceilingFan.off();
        }
    }
}
Light
package Chapter6_CommandPattern.ElectricAppliance;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

public class Light {
    String name;

    public Light(String name){
        this.name = name;
    }

    public void on(){
        System.out.println(this.name+" light is on!");
    }
    public void off(){
        System.out.println(this.name+" light is off!");
    }
}
LightOnCommand
package Chapter6_CommandPattern.Command;

import Chapter6_CommandPattern.Command.Command;
import Chapter6_CommandPattern.ElectricAppliance.Light;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

public class LightOnCommand implements Command {
    Light light;

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

    @Override
    public void execute() {
        //当遥控器运行这个指令的时候,并不知道灯是如何实现打开开关的
        //实现遥控器与电器之间的解耦合
        this.light.on();
    }

    @Override
    public void undo() {
        this.light.off();
    }
}
LightOffCommand
package Chapter6_CommandPattern.Command;

import Chapter6_CommandPattern.ElectricAppliance.Light;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

public class LightOffCommand implements Command{
    Light light;

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

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

    public void undo() {
        this.light.on();
    }
}
GarageDoor
package Chapter6_CommandPattern.ElectricAppliance;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

public class GarageDoor {
    Light light;

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

    public void up(){
        this.lightOn();
        System.out.println("the garage door is open!");
    }

    public void down(){
        this.lightOff();
        System.out.println("the garage door is closed");
    }

    private void lightOn(){
        this.light.on();
    }

    private void lightOff(){
        this.light.off();
    }
}
GarageDoorOpenCommand
package Chapter6_CommandPattern.Command;

import Chapter6_CommandPattern.ElectricAppliance.GarageDoor;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

public class GarageDoorOpenCommand implements Command{
    GarageDoor garageDoor;

    public GarageDoorOpenCommand(GarageDoor garageDoor){
        this.garageDoor = garageDoor;
    }

    @Override
    public void execute() {
        this.garageDoor.up();
    }

    public void undo() {
        this.garageDoor.down();
    }
}
GarageDoorCloseCommand
package Chapter6_CommandPattern.Command;

import Chapter6_CommandPattern.ElectricAppliance.GarageDoor;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

public class GarageDoorCloseCommand implements Command{
    GarageDoor garageDoor;

    public GarageDoorCloseCommand(GarageDoor garageDoor){
        this.garageDoor = garageDoor;
    }

    @Override
    public void execute() {
        this.garageDoor.down();
    }

    public void undo() {
        this.garageDoor.down();
    }
}
Stereo
package Chapter6_CommandPattern.ElectricAppliance;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

public class Stereo {
    int volume;
    //音响类
    public void on(){
        System.out.println("the stereo is on!");
    }
    public void off(){
        System.out.println("the stereo is off!");
    }

    public void setCD(){
        System.out.println("the stereo can work with CD now!");
    }

    public void setDVD(){
        System.out.println("the stereo can work with DVD now!");
    }

    public void setVolume(int volume){//设置音量
        this.volume = volume;
    }
}
StereoOnWithCDCommand
package Chapter6_CommandPattern.Command;

import Chapter6_CommandPattern.ElectricAppliance.Stereo;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

public class StereoOnWithCDCommand implements Command{
    Stereo stereo;

    public StereoOnWithCDCommand(Stereo stereo){
        this.stereo = stereo;
    }

    @Override
    public void execute() {
        this.stereo.on();
        this.stereo.setCD();
        this.stereo.setVolume(6);
    }

    @Override
    public void undo() {
        this.stereo.off();
    }
}
StereoOff
package Chapter6_CommandPattern.Command;

import Chapter6_CommandPattern.ElectricAppliance.Stereo;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

public class StereoOff implements  Command{
    Stereo stereo;

    public StereoOff(Stereo stereo){
        this.stereo = stereo;
    }

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

    public void undo() {
        this.stereo.on();
        this.stereo.setCD();
        this.stereo.setVolume(6);
    }
}
MacroCommand
package Chapter6_CommandPattern.Command;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

//宏指令
public class MacroCommand implements Command{
    Command[] commands;
    public MacroCommand(Command[] commands){
        this.commands = commands;
    }

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

    @Override
    public void undo() {
        for(int i=0;i<this.commands.length;++i){
            this.commands[i].undo();
        }
    }
}
NoCommand
package Chapter6_CommandPattern.Command;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

public class NoCommand implements Command{
    @Override
    public void execute() {
        //this command is useless!
    }

    @Override
    public void undo() {

    }
}
RemoteControl
package Chapter6_CommandPattern;

import Chapter6_CommandPattern.Command.Command;
import Chapter6_CommandPattern.Command.NoCommand;

import java.util.Arrays;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

//遥控器类
public class RemoteControl {
    Command[] onCommands;
    Command[] offCommands;
    Command undoCommand;

    public RemoteControl(){
        //为简洁起见,这里遥控器只有3个槽位
        this.onCommands = new Command[7];
        this.offCommands = new Command[7];

        Command noCommand = new NoCommand();
        //这里使用空对象,是为了后面不用写 if(onCommand[i]==null){...}
        for(int i =0;i<7;++i){
            this.onCommands[i] = noCommand;
            this.offCommands[i] = noCommand;
        }
        this.undoCommand = noCommand;
    }

    //设置某个电器的开关命令
    public void setCommand(int slot, Command onCommand, Command offCommand){
        this.onCommands[slot] = onCommand;
        this.offCommands[slot] = offCommand;
    }

    public void onButtonWasPushed(int slot){
        this.onCommands[slot].execute();
        this.undoCommand = this.onCommands[slot];
    }

    public void offButtonWasPushed(int slot){
        this.offCommands[slot].execute();
        this.undoCommand = this.offCommands[slot];
    }

    public void undoButtonWasPushed(){
        this.undoCommand.undo();
    }

    @Override
    public String toString() {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("\n---------- Remote Control ----------\n");
        for(int i = 0;i<this.onCommands.length;i++){
            stringBuffer.append("[slot "+ i +"] "+
                    String.format("%-30s",this.onCommands[i].getClass().getSimpleName())+
                    String.format("%-30s",this.offCommands[i].getClass().getSimpleName())+"\n"
            );
        }
        stringBuffer.append("[undo] "+this.undoCommand.getClass().getSimpleName());
        return stringBuffer.toString();
    }
}
RemoteLoader
package Chapter6_CommandPattern;

import Chapter6_CommandPattern.Command.*;
import Chapter6_CommandPattern.ElectricAppliance.CeilingFan;
import Chapter6_CommandPattern.ElectricAppliance.GarageDoor;
import Chapter6_CommandPattern.ElectricAppliance.Light;
import Chapter6_CommandPattern.ElectricAppliance.Stereo;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

public class RemoteLoader {
    public static void main(String[] args) {
        RemoteControl remoteControl = new RemoteControl();

        //创建设备
        Light LivingRoomLight = new Light("LivingRoom");
        Light KitchenLight = new Light("Kitchen");
        Light GarageLight = new Light("Garage");
        GarageDoor garageDoor = new GarageDoor(GarageLight);
        Stereo stereo = new Stereo();

        //创建命令对象
        LightOnCommand livingRoomLightOn =new LightOnCommand(LivingRoomLight);
        LightOnCommand kitchenLightOn = new LightOnCommand(KitchenLight);
        GarageDoorOpenCommand garageDoorOpenCommand =
                new GarageDoorOpenCommand(garageDoor);
        StereoOnWithCDCommand stereoOnWithCDCommand =
                new StereoOnWithCDCommand(stereo);

        LightOffCommand lightOffCommand = new LightOffCommand(LivingRoomLight);
        LightOffCommand kitchenLightOff = new LightOffCommand(KitchenLight);
        GarageDoorCloseCommand garageDoorCloseCommand =
                new GarageDoorCloseCommand(garageDoor);
        StereoOff stereoOff = new StereoOff(stereo);

        //将命令加载进入槽位
        remoteControl.setCommand(0,livingRoomLightOn,lightOffCommand);
        remoteControl.setCommand(1,kitchenLightOn,kitchenLightOff);
        remoteControl.setCommand(2,garageDoorOpenCommand,garageDoorCloseCommand);
        remoteControl.setCommand(3,stereoOnWithCDCommand,stereoOff);

        //展示
//        System.out.println(remoteControl);

        remoteControl.onButtonWasPushed(0);
        remoteControl.onButtonWasPushed(1);
        remoteControl.onButtonWasPushed(2);
        remoteControl.onButtonWasPushed(3);

        remoteControl.offButtonWasPushed(0);
        remoteControl.offButtonWasPushed(1);
        remoteControl.offButtonWasPushed(2);
        remoteControl.offButtonWasPushed(3);

        //使用lambda简洁编写代码
        //增加撤销按钮后就不能使用了
        //这样就不用写一大堆命令类了
//        remoteControl.setCommand(4,()->LivingRoomLight.on(),
//                ()->LivingRoomLight.off());

        //测试撤销功能
        System.out.println("\n测试撤销:");
        remoteControl.onButtonWasPushed(0);
        remoteControl.undoButtonWasPushed();

        //测试风扇
        System.out.println("test fan");
        CeilingFan ceilingFan = new CeilingFan("livingRoom");
        CeilingFanHighCommand command = new CeilingFanHighCommand(ceilingFan);
        remoteControl.setCommand(4,command,command);

        System.out.println(remoteControl);

        remoteControl.onButtonWasPushed(4);
        System.out.println(remoteControl);

        remoteControl.undoButtonWasPushed();

        //测试宏指令
        System.out.println("\n宏指令");
        Light light1 = new Light("Room1");
        Light light2 = new Light("Room2");
        Light light3 = new Light("Room3");
        Light light4 = new Light("Room4");

        LightOnCommand lightOnCommand1 = new LightOnCommand(light1);
        LightOnCommand lightOnCommand2 = new LightOnCommand(light2);
        LightOnCommand lightOnCommand3 = new LightOnCommand(light3);
        LightOnCommand lightOnCommand4 = new LightOnCommand(light4);

        LightOffCommand lightOffCommand1 = new LightOffCommand(light1);
        LightOffCommand lightOffCommand2 = new LightOffCommand(light2);
        LightOffCommand lightOffCommand3 = new LightOffCommand(light3);
        LightOffCommand lightOffCommand4 = new LightOffCommand(light4);

        Command[] onCommands = {lightOnCommand1,lightOnCommand2,lightOnCommand3,lightOnCommand4};
        Command[] offCommand = {lightOffCommand1,lightOffCommand2,lightOffCommand3,lightOffCommand4};
        MacroCommand partyOn = new MacroCommand(onCommands);
        MacroCommand partyOff = new MacroCommand(offCommand);

        remoteControl.setCommand(5,partyOn,partyOff);

        System.out.println(remoteControl);
        remoteControl.onButtonWasPushed(5);
        remoteControl.offButtonWasPushed(5);
        remoteControl.undoButtonWasPushed();


    }
}
SimpleRemoteControl
package Chapter6_CommandPattern;

import Chapter6_CommandPattern.Command.Command;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

public class SimpleRemoteControl {
    Command slot;//目前该遥控器只支持一个槽位

    public SimpleRemoteControl(){}

    public void setCommand(Command command){
        this.slot = command;
    }

    public void buttonWasPressed(){
        this.slot.execute();
    }

}
RemoteControlTest
package Chapter6_CommandPattern;

import Chapter6_CommandPattern.Command.GarageDoorOpenCommand;
import Chapter6_CommandPattern.ElectricAppliance.GarageDoor;
import Chapter6_CommandPattern.ElectricAppliance.Light;

/**
 * @Author 竹心
 * @Date 2023/8/6
 **/

public class RemoteControlTest {
    public static void main(String[] args) {
        SimpleRemoteControl remote = new SimpleRemoteControl();
        Light light = new Light("garage light");
        GarageDoor garageDoor = new GarageDoor(light);
        GarageDoorOpenCommand garageDoorOpen = new GarageDoorOpenCommand(garageDoor);

        remote.setCommand(garageDoorOpen);
        remote.buttonWasPressed();
    }
}
notes.txt
命令模式:
    把请求封装成为对象,以便对不同的请求、队列或者日志请求来参数化对象,
    并支持可撤销的操作

命令对象只暴露一个方法:execute(),命令的请求者不会知道执行者具体如何实现指令

当需要将发出请求的对象和能够实行请求的对象解耦合的时候可以使用命令模式

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/62143.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

使用Socket实现TCP版的回显服务器

文章目录 1. Socket简介2. ServerSocket3. Socket4. 服务器端代码5. 客户端代码 1. Socket简介 Socket&#xff08;Java套接字&#xff09;是Java编程语言提供的一组类和接口&#xff0c;用于实现网络通信。它基于Socket编程接口&#xff0c;提供了一种简单而强大的方式来实现…

华云安参编的《云原生安全配置基线规范》正式发布

由中国信息通信研究院&#xff08;以下简称“中国信通院”&#xff09;、中国通信标准化协会主办的第十届可信云大会云原生安全分论坛于7月26日在北京国际会议中心成功召开。作为大会上展示的成果之一&#xff0c;由中国信通院联合行业领先企业共同编写的《云原生安全配置基线规…

剑指 Offer 53 - II. 0~n-1中缺失的数字

题目描述 一个长度为n-1的递增排序数组中的所有数字都是唯一的&#xff0c;并且每个数字都在范围0&#xff5e;n-1之内。在范围0&#xff5e;n-1内的n个数字中有且只有一个数字不在该数组中&#xff0c;请找出这个数字。示例 解答 一眼二分法 class Solution {public int mi…

java中使用Jsoup和Itext实现将html转换为PDF

1.在build.gradle中安装所需依赖&#xff1a; implementation group: com.itextpdf, name: itextpdf, version: 5.5.13 implementation group: com.itextpdf.tool, name: xmlworker, version: 5.5.13 implementation group: org.jsoup, name: jsoup, version: 1.15.32.创建工具…

物联网|按键实验---学习I/O的输入及中断的编程|函数说明的格式|如何使用CMSIS的延时|读取通过外部中断实现按键捕获代码的实现及分析-学习笔记(14)

文章目录 通过外部中断实现按键捕获代码的实现及分析Tip1:函数说明的格式Tip2:如何使用CMSIS的延时GetTick函数原型stm32f407_intr_handle.c解析中断处理函数&#xff1a;void EXTI4_IRQHandler 调试流程软件模拟调试 两种代码的比较课后作业: 通过外部中断实现按键捕获代码的实…

网络安全【黑客】自学

1.什么是网络安全&#xff1f; 网络安全可以基于攻击和防御视角来分类&#xff0c;我们经常听到的 “红队”、“渗透测试” 等就是研究攻击技术&#xff0c;而“蓝队”、“安全运营”、“安全运维”则研究防御技术。 无论网络、Web、移动、桌面、云等哪个领域&#xff0c;都有…

【云原生】K8S二进制搭建三:高可用配置

目录 一、部署CoreDNS二、配置高可用三、配置负载均衡四、部署 Dashboard 一、部署CoreDNS 在所有 node 节点上操作 #上传 coredns.tar 到 /opt 目录中 cd /opt docker load -i coredns.tar在 master01 节点上操作 #上传 coredns.yaml 文件到 /opt/k8s 目录中&#xff0c;部…

【 stable diffusion LORA模型训练最全最详细教程】

个人网站&#xff1a;https://tianfeng.space/ 文章目录 一、前言二、朱尼酱的赛博丹炉1.介绍2.解压配置3.使用训练准备首页设置上传素材查看进度 三、秋叶的lora训练器1.下载2.预处理3.参数调配 一、前言 其实想写LORA模型训练很久了&#xff0c;一直没时间&#xff0c;总结…

React Native从文本内容尾部截取显示省略号

<Textstyle{styles.mMeNickname}ellipsizeMode"tail"numberOfLines{1}>{userInfo.nickname}</Text> 参考链接&#xff1a; https://www.reactnative.cn/docs/text#ellipsizemode https://chat.xutongbao.top/

MySQL语句性能分析与优化

目录 SQL性能分析 SQL执行频率 SQL慢查询日志 Profile Explain SQL优化 插入数据的优化 主键优化 Order By优化 Group By优化 Limit 优化 Count 优化 Update 优化 多表连接查询优化 SQL性能分析 通过SQL性能分析来做SQL的优化&#xff0c;主要是优化SQL的查询语…

java中javamail发送带附件的邮件实现方法

java中javamail发送带附件的邮件实现方法 本文实例讲述了java中javamail发送带附件的邮件实现方法。分享给大家供大家参考。具体分析如下&#xff1a; JavaMail&#xff0c;顾名思义&#xff0c;提供给开发者处理电子邮件相关的编程接口。它是Sun发布的用来处理email的API。它…

Java-day06(面向对象-2)

面向对象 参数 参数分为形参(方法声明时的参数)与实参&#xff08;方法调用时实际传给形参的参数值&#xff09; 将对象作为参数传递给方法 &#xff08;1&#xff09;定义一个Circle类,包含一个double型是r属性代表圆的半径&#xff0c;一个findArea()方法返回圆的面积。 …

static关键字

作者简介&#xff1a; zoro-1&#xff0c;目前大一&#xff0c;正在学习Java&#xff0c;数据结构等 作者主页&#xff1a; zoro-1的主页 欢迎大家点赞 &#x1f44d; 收藏 ⭐ 加关注哦&#xff01;&#x1f496;&#x1f496; 被static修饰意味什么 在Java中&#xff0c;被st…

ld加上-static -lc参数报错`ld: cannot find -lc`处理方法

cat /etc/redhat-release看到操作系统是CentOS Linux release 7.6.1810&#xff0c;uname -r看到内核版本是3.10.0-957.el7.x86_64&#xff0c;as --version看到as的版本是2.27-34.base.el7&#xff0c;ld --version看到ld的版本是2.27-34.base.el7。 absCallWithStart.s里边…

33.利用abs 解决绝对值问题(matlab程序 )

1.简述 abs函数的功能是绝对值和复数的模 语法 Y abs(X) 说明 Y abs(X) 返回数组 X 中每个元素的绝对值。如果 X 是复数&#xff0c;则 abs(X) 返回复数的模。 示例 标量的绝对值 y abs(-5) y 5 向量的绝对值 创建实值的数值向量。 x [1.3 -3.56 8.23 -5 -0.01…

MacOS上用docker运行mongo及mongo-express

MongoDB简介 MongoDB 是一个基于分布式文件存储的数据库。由 C 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。 MongoDB 是一个介于关系数据库和非关系数据库之间的产品&#xff0c;是非关系数据库当中功能最丰富&#xff0c;最像关系数据库的。 前提 要求…

ChatGPT: 人机交互的未来

ChatGPT: 人机交互的未来 ChatGPT背景ChatGPT的特点ChatGPT的应用场景结论 ChatGPT ChatGPT是一种基于大数据和机器学习的人工智能聊天机器人模型。它由国内团队发明、开发&#xff0c;并被命名为Mental AI。ChatGPT的目标是通过模拟自然对话的方式&#xff0c;提供高效、智能…

vscode中无法使用git解决方案

1 首先查看git安装目录 where git 2 找到bash.exe 的路径 比如&#xff1a;C:/Users/Wangzd/AppData/Local/Programs/Git/bin/bash 3 找到vscode的配置项setting.json 4 添加 "terminal.integrated.shell.windowns": "C:/Users/Wangzd/AppData/Local/Pr…

SpringBoot中Redis报错:NOAUTH Authentication required

1、问题 org.springframework.dao.InvalidDataAccessApiUsageException: NOAUTH Authentication required.; nested exception is redis.clients.jedis.exceptions.JedisDataException: NOAUTH Authentication required. … 2、解决 如果提供了密码还没解决&#xff0c;那可能是…

【剑指Offer 06】从尾到头打印链表,Java解密。

LeetCode 剑指Offer 75道练习题 文章目录 剑指Offer&#xff1a;从尾到头打印链表示例&#xff1a;限制&#xff1a;解题思路&#xff1a; 剑指Offer&#xff1a;从尾到头打印链表 【题目描述】 输入一个链表的头节点&#xff0c;从尾到头反过来返回每个节点的值&#xff08;用…