Command Pattern
golang学习网今天将给大家带来《Command Pattern》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习文章或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!
什么是命令模式?
命令模式是一种行为模式,它将请求封装为独立的对象,从而使您可以将请求作为方法参数传递、对请求进行排队或记录请求,并支持可撤消的操作。
什么时候使用它?
- 当您需要将发出请求的对象与知道如何执行请求的对象解耦时,请使用命令模式。
- 当您想在运行时向对象注入或分配不同的请求时,请使用命令模式。
- 当您需要在应用程序中进行撤消或重做操作时,请使用命令模式。
问题
想象一下,我们正在为远程控制设计 api,用于操作客户端中的电子设备。这里我们有很多供应商课程。
引入通用接口似乎并不有趣,因为我们的 vender 类是多种多样的,并且预计我们会有更多的 vender 类。
此外,遥控器不应包含一组 if 语句,例如 if slot1 == light, then light.turnon(),else if slot1 == tv, then tv.turnon(),因为它是一个糟糕的设计。
解决方案
简单地说,我们希望远程控制知道如何发出通用请求,但不关心特定的供应商类。为了实现这一目标,我们将把我们的关注点分为两类,一类提出请求,另一类实际执行工作以遵守请求。
远程控制
这是发出诸如 command.execute() 之类的请求的请求,但不关心如何执行工作。
如果您希望 remotecontrol 有多个插槽(例如,一个用于 outdoorlight,另一个用于 tv),remotecontrol 可以具有命令数组,例如 oncommands[] 和 offcommands[]。 setcommand 方法可以采用一个整数来确定要设置的槽。例如,setcommand(2, tvoncommand, tvoffcommand) 可能会将 tvoncommand 分配给 oncommands[2],将 tvoffcommand 分配给 offcommands[2]。命令
为所有concretecommands提供接口。具体命令
turnonoutdoorlightcommand 对象调用execute() 方法并将“如何打开灯”委托给持有的ourdoorlight 对象。户外灯
这是知道如何执行工作以遵守 remotecontrol 请求的人。客户
client 负责创建 concretecommands 并将它们与相应的 receiver 关联起来。
结构
java实现
// receiver public class outdoorlight { public void turnon() { system.out.println("outdoor light is on"); } public void turnoff() { system.out.println("outdoor light is off"); } }
public interface command { void execute(); void undo(); }
// concrete command public class turnonoutdoorcommand implements command { private outdoorlight outdoorlight; public turnonoutdoorcommand(outdoorlight outdoorlight) { this.outdoorlight = outdoorlight; } @override public void execute() { outdoorlight.turnon(); } @override public void undo() { outdoorlight.turnoff(); } }
// concrete command public class turnoffoutdoorlightcommand implements command { outdoorlight outdoorlight; public turnoffoutdoorlightcommand(outdoorlight outdoorlight) { this.outdoorlight = outdoorlight; } @override public void execute() { outdoorlight.turnoff(); } @override public void undo() { outdoorlight.turnon(); } }
// null object public class nocommand implements command { @override public void execute() { } @override public void undo() { } }
// invoker public class remotecontrol { private command oncommand; private command offcommand; public stackundocommands; public remotecontrol() { oncommand = new nocommand(); offcommand = new nocommand(); undocommands = new stack<>(); undocommands.push(new nocommand()); } public void setcommand(command oncommand, command offcommand) { this.oncommand = oncommand; this.offcommand = offcommand; } public void onbuttonwaspushed() { oncommand.execute(); undocommands.push(oncommand); } public void offbuttonwaspushed() { offcommand.execute(); undocommands.push(offcommand); } public void undobuttonwaspushed() { if (!(undocommands.peek() instanceof nocommand)) { command lastcommand = undocommands.pop(); lastcommand.undo(); } else { system.out.println("undocommands stack is empty!"); } } }
public class client { public static void main(string[] args) { outdoorlight outdoorlight = new outdoorlight(); // create a receiver // create commands on that receiver // these commands are encapsulated requests in other words command turnonoutdoorlight = new turnonoutdoorcommand(outdoorlight); command turnoffoutdoorlight = new turnoffoutdoorlightcommand(outdoorlight); remotecontrol rc = new remotecontrol(); // create an invoker // we can pass encapsulated requests to other object rc.setcommand(turnonoutdoorlight, turnoffoutdoorlight); // set command on that invoker rc.undobuttonwaspushed(); rc.onbuttonwaspushed(); rc.offbuttonwaspushed(); rc.undobuttonwaspushed(); rc.undobuttonwaspushed(); rc.undobuttonwaspushed(); } }
输出:
undocommands stack is empty! outdoor light is on outdoor light is off outdoor light is on outdoor light is off undocommands stack is empty!
nocommand 被称为 null object,这是另一种设计模式。当您没有要返回的含义对象时,它很有用。这里我们使用它作为 invoker 持有的默认命令,这样我们就不需要处理 null。
陷阱
- 客户端需要做很多事情,例如创建concretecommands并设置相应的receiver,创建invoker并在该invoker上设置concretecommands。
宏命令
macrocommand 是命令模式的简单扩展,它允许您使用一个命令来打开灯、电视、空调、咖啡机和播放音乐。
让我们创建一种新的命令来执行一组其他命令。
public class macrocommand implements command { command[] commands; public macrocommand(command[] commands) { this.commands = commands; } // executes holding commands one at a time @override public void execute() { for (command command : commands) { command.execute(); } } }
就是这样!现在我们准备好使用宏命令了。但在此之前,让我向您展示如何实现可以有多个插槽的 remotecontrol,正如我在“解决方案”部分中提到的。
public class remotecontrol { private command[] oncommands; private command[] offcommands; public remotecontrol() { // our remotecontrol has 3 slots oncommands = new command[3]; offcommands = new command[3]; command nocommand = new nocommand(); for (int i = 0; i < oncommands.length; i++) { oncommands[i] = nocommand; offcommands[i] = nocommand; } } public void setcommands(int slot, command oncommand, command offcommand) { oncommands[slot] = oncommand; offcommands[slot] = offcommand; } public void onbuttonwaspushed(int slot) { oncommands[slot].execute(); } public void offbuttonwaspushed(int slot) { offcommands[slot].execute(); } // print slots info in pretty style @override public string tostring() { stringbuilder stringbuilder = new stringbuilder(); stringbuilder.append("\n------ remote control ------\n"); for (int i = 0; i < oncommands.length; i++) { stringbuilder.append("[slot " + i + "] " + oncommands[i].getclass().getsimplename() + " " + offcommands[i].getclass().getsimplename() + "\n"); } return stringbuilder.tostring(); } }
很简单,用数组来存储多个命令即可。
最后,客户端使用我们的宏命令。为了简单起见,我只创建了两个接收器,light 和 coffeemachine。
public class client { public static void main(string[] args) { // create receivers light light = new light(); coffeemachine coffeemachine = new coffeemachine(); // create commands and set corresponding receivers on them command lightoncommand = new lightoncommand(light); command lightoffcommand = new lightoffcommand(light); command coffeemachineoncommand = new coffeemachineon(coffeemachine); command coffeemachineoffcommand = new coffeemachineoff(coffeemachine); // create arrays of commands command[] morningon = {lightoncommand, coffeemachineoncommand}; command[] morningoff = {lightoffcommand, coffeemachineoffcommand}; // create macros macrocommand morningonmacro = new macrocommand(morningon); macrocommand morningoffmacro = new macrocommand(morningoff); remotecontrol rc = new remotecontrol(); rc.setcommands(0, morningonmacro, morningoffmacro); system.out.println(rc); system.out.println("--- pushing macro on ---"); rc.onbuttonwaspushed(0); system.out.println("\n--- pushing macro off ---"); rc.offbuttonwaspushed(0); } }
输出:
------ remote control ------ [slot 0] macrocommand macrocommand [slot 1] nocommand nocommand [slot 2] nocommand nocommand --- pushing macro on --- light is on coffee machine is on coffee machine is making a cup of coffee --- pushing macro off --- light is off coffee machine is off
我们的宏命令打开灯并启动咖啡机,咖啡机立即开始冲泡咖啡。请注意,我们可以在 receiver 中定义一组操作,并在 concretecommand 的execute() 方法中使用它们,如“结构”部分中的 uml 图所示。
@Override public void execute() { coffeeMachine.on(); coffeeMachine.makeCoffee(); }
您可以在这里查看所有设计模式的实现。
github 存储库
附注
我是刚开始写科技博客,如果您对我的写作有什么建议,或者有任何困惑的地方,请留言!
感谢您的阅读:)
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于文章的相关知识,也可关注golang学习网公众号。

- 上一篇
- 中国移动 30 元面额话费充值在福建等六省份微信、支付宝下架

- 下一篇
- PHP中如何使用CMD命令登录共享文件夹并复制文件?
-
- 文章 · java教程 | 14小时前 | eclipse 设置步骤 中文界面 IntelliJIDEA 字体显示
- Java开发工具中文界面设置教程
- 169浏览 收藏
-
- 文章 · java教程 | 15小时前 |
- Java、Python、C语言三者区别详解
- 328浏览 收藏
-
- 文章 · java教程 | 15小时前 |
- Java必备知识点详解,体系结构全解析
- 270浏览 收藏
-
- 文章 · java教程 | 21小时前 |
- HBase配置文件测试及Kerberos认证连接问题解决
- 351浏览 收藏
-
- 文章 · java教程 | 1天前 |
- 学Java必备知识点全解析,Java体系详解
- 133浏览 收藏
-
- 文章 · java教程 | 1天前 |
- 反序输出字符串:填码验证算法小练习
- 278浏览 收藏
-
- 文章 · java教程 | 2天前 |
- Java非C语言开发,揭秘Java技术实现
- 236浏览 收藏
-
- 文章 · java教程 | 2天前 |
- Java学习必备知识体系结构详解
- 237浏览 收藏
-
- 文章 · java教程 | 2天前 |
- 若依框架MyBatis依赖配置及查找方法
- 194浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- AI Make Song
- AI Make Song是一款革命性的AI音乐生成平台,提供文本和歌词转音乐的双模式输入,支持多语言及商业友好版权体系。无论你是音乐爱好者、内容创作者还是广告从业者,都能在这里实现“用文字创造音乐”的梦想。平台已生成超百万首原创音乐,覆盖全球20个国家,用户满意度高达95%。
- 2次使用
-
- SongGenerator
- 探索SongGenerator.io,零门槛、全免费的AI音乐生成器。无需注册,通过简单文本输入即可生成多风格音乐,适用于内容创作者、音乐爱好者和教育工作者。日均生成量超10万次,全球50国家用户信赖。
- 2次使用
-
- BeArt AI换脸
- 探索BeArt AI换脸工具,免费在线使用,无需下载软件,即可对照片、视频和GIF进行高质量换脸。体验快速、流畅、无水印的换脸效果,适用于娱乐创作、影视制作、广告营销等多种场景。
- 2次使用
-
- 协启动
- SEO摘要协启动(XieQiDong Chatbot)是由深圳协启动传媒有限公司运营的AI智能服务平台,提供多模型支持的对话服务、文档处理和图像生成工具,旨在提升用户内容创作与信息处理效率。平台支持订阅制付费,适合个人及企业用户,满足日常聊天、文案生成、学习辅助等需求。
- 9次使用
-
- Brev AI
- 探索Brev AI,一个无需注册即可免费使用的AI音乐创作平台,提供多功能工具如音乐生成、去人声、歌词创作等,适用于内容创作、商业配乐和个人创作,满足您的音乐需求。
- 10次使用
-
- 提升Java功能开发效率的有力工具:微服务架构
- 2023-10-06 501浏览
-
- 掌握Java海康SDK二次开发的必备技巧
- 2023-10-01 501浏览
-
- 如何使用java实现桶排序算法
- 2023-10-03 501浏览
-
- Java开发实战经验:如何优化开发逻辑
- 2023-10-31 501浏览
-
- 如何使用Java中的Math.max()方法比较两个数的大小?
- 2023-11-18 501浏览