首页 > 其他分享 >设计模式之命令模式

设计模式之命令模式

时间:2023-12-25 22:36:11浏览次数:30  
标签:slot cjn light void 模式 命令 设计模式 com public

(命令模式)

命令模式

将方法调用封装起来,通过封装方法调用,将运算块包装成型。调用次运算的对象不需要关心事情是如何进行的,只要知道如何使用包装成型的方法来完成它就可以。应用于记录日志,或者重复使用这些封装来实现撤销。

命令模式可将“动作的请求者”从“动作的执行者”对象中解耦。

定义

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

1703510563146.png

  • receiver 接受者角色
  • command 命令角色
  • invoker 调用者角色

代码实现

  1. Receiver

    public class Light {
        String roomName;
        public Light(String room) {
            this.roomName = room;
        }
        public void on() {
            System.out.println(roomName + " light on...");
        }
    
        public void off() {
            System.out.println(roomName + " light off...");
        }
    
        public void noCommand() {
            System.out.println("no Command...");
        }
    }
    
  2. Command

    public interface Command {
        public void execute();
        public void undo();
    }
    
    /**
     *开灯
     */
    public class LightOnCommond implements Command {
        Light light;
        public LightOnCommond(Light light) {
            this.light = light;
        }
        @Override
        public void execute() {
            light.on();
        }
    
        @Override
        public void undo() {
            light.off();
        }
    }
    
    /**
     *关灯
     */
    public class LightOffCommond implements Command {
        Light light;
        public LightOffCommond(Light light) {
            this.light = light;
        }
        @Override
        public void execute() {
            light.off();
        }
    
        @Override
        public void undo() {
            light.on();
        }
    }
    
  3. Invoker

    public class RemoteController {
        Command[] onCommands;
        Command[] offCommands;
        Command undoCommand;
    
        public RemoteController() {
            onCommands = new Command[7];
            offCommands = new Command[7];
    
            Command noCommand = new NoCommand();
    
            for (int i = 0; i < 7; i++) {
                onCommands[i] = noCommand;
                offCommands[i] = noCommand;
            }
            undoCommand = noCommand;
        }
    
        public void setCommand(int slot, Command onCommand, Command offCommand) {
            onCommands[slot] = onCommand;
            offCommands[slot] = offCommand;
        }
    
        public void onButtonWasPushed(int slot) {
            onCommands[slot].execute();
            undoCommand = onCommands[slot];
        }
    
        public void offButtonWasPushed(int slot) {
            offCommands[slot].execute();
            undoCommand = offCommands[slot];
        }
    
        public void undoButtonWasPushed() {
            undoCommand.undo();
        }
    
        public String toString() {
            StringBuffer stringBuff = new StringBuffer();
            stringBuff.append("\n------ Remote Controller ------\n");
            for (int i = 0; i < onCommands.length; i++) {
                stringBuff.append("[slot " + i + "] " + onCommands[i].getClass().getName()
                        + "    " + offCommands[i].getClass().getName() + "\n");
            }
            return stringBuff.toString();
        }
    }
    
  4. 测试代码

    public class RemoteLoader {
        public static void main(String[] args) {
            RemoteController remoteController = new RemoteController();
            Light livingRoomLight =  new Light("Living Room");
            Light kitchenLight =  new Light("Kitchen");
    
            LightOnCommond livingRoomLightOn = new LightOnCommond(livingRoomLight);
            LightOffCommond livingRoomLightOff = new LightOffCommond(livingRoomLight);
            LightOnCommond kitchenLightOn = new LightOnCommond(kitchenLight);
            LightOffCommond kitchenLightOff = new LightOffCommond(kitchenLight);
    
            remoteController.setCommand(0, livingRoomLightOn, livingRoomLightOff);
            remoteController.setCommand(1, kitchenLightOn, kitchenLightOff);
    
            System.out.println(remoteController);
    
            remoteController.onButtonWasPushed(0);
            remoteController.offButtonWasPushed(0);
            remoteController.onButtonWasPushed(1);
            remoteController.offButtonWasPushed(1);
        }
    }
    
  5. 输出结果

    ------ Remote Controller ------
    [slot 0] com.cjn.LightOnCommond    com.cjn.LightOffCommond
    [slot 1] com.cjn.LightOnCommond    com.cjn.LightOffCommond
    [slot 2] com.cjn.NoCommand    com.cjn.NoCommand
    [slot 3] com.cjn.NoCommand    com.cjn.NoCommand
    [slot 4] com.cjn.NoCommand    com.cjn.NoCommand
    [slot 5] com.cjn.NoCommand    com.cjn.NoCommand
    [slot 6] com.cjn.NoCommand    com.cjn.NoCommand
    
    Living Room light on...
    Living Room light off...
    Kitchen light on...
    Kitchen light off...
    

标签:slot,cjn,light,void,模式,命令,设计模式,com,public
From: https://blog.51cto.com/u_16370137/8972645

相关文章

  • Docker常用基础命令
    Docker常用命令常规帮助启动类命令启|停|重启|状态|开机自启命令systemctlstart|stop|restart|status|enabledocker查看docker概要信息dockerinfo查看docker总体帮助文档docker--help查看docker命令帮助文档docker具体命令--help镜像命令dockerimag......
  • c# 责任链模式
    责任链模式是一种行为型设计模式,它允许多个对象按照链式结构处理请求,直到有对象能够处理请求为止。在C#中,责任链模式通常通过构建一个处理请求的链来实现。下面是一个简单的示例:首先,定义一个处理请求的抽象基类Handler,该类包含一个指向下一个处理者的引用:publicabstractclass......
  • C# 适配器模式
    适配器模式是一种结构型设计模式,它可以将一个或多个不兼容的接口适配成客户端期望的接口。在C#中,适配器模式通常采用类适配器或对象适配器的方式实现。下面是一个简单的类适配器示例:首先,定义一个客户端期望的目标接口,例如ICircle:publicinterfaceICircle{voidDraw(intx......
  • 迭代器模式揭秘:如何优雅应对数据遍历
    推荐语在这篇文章中,深入探讨了迭代器模式的核心原理和实战应用。通过清晰而有条理的解释,读者小伙伴可以领悟到迭代器模式在数据遍历和管理方面的强大能力。无论是初学者还是有经验的开发者,都能从这篇文章中获得实用的知识和技巧,进一步提升代码的可读性和可维护性。什么是迭代器模......
  • 前端学习笔记202310学习笔记第一百贰拾贰天-nodejs-命令行操作29
    ......
  • 前端学习笔记202310学习笔记第一百贰拾贰天-nodejs-命令行操作29
    ......
  • 线程池模式
    概念线程池模式(ThreadPoolPattern)是一种用于管理线程的设计模式。它通过预先创建一组线程,并维护一个任务队列,将需要执行的任务提交给线程池来执行,从而避免了频繁地创建和销毁线程的开销,提供了线程的重用和线程生命周期的管理。线程池模式的主要目标是提高线程的利用率、减少线......
  • jenkins报"node"不是内部或外部命令,也不是可运行的程序或批处理文件。
    解决方法:1、配置node的环境变量2、配置系统环境变量:3、配置Jenkins环境变量path值:win+R,cmd,输入path获得......
  • docker常用命令
    以下是一些常用的Docker命令,以帮助您管理Docker容器和镜像:容器生命周期管理:启动容器:dockerstart<容器ID或名称>停止容器:dockerstop<容器ID或名称>重启容器:dockerrestart<容器ID或名称>进入容器:dockerexec-it<容器ID或名称>/bin/bash容器信息查看:查看......
  • 备忘录模式(Memento)
    #include<iostream>#include<string>usingnamespacestd;classOriginalWord;classMemento{public:Memento(stringstrWord):m_strWord(strWord){}private:friendclassOriginalWord;stringGetWords(){returnm_strWord......