[设计模式]命令模式(Command)

命令模式很好理解,举个例子,司令员下令让士兵去干件事情,从整个事情的角度来考虑,司令员的作用是,发出口令,口令经过传递,传到了士兵耳朵里,士兵去执行。这个过程好在,三者相互解耦,任何一方都不用去依赖其他人,只需要做好自己的事儿就行,司令员要的是结果,不会去关注到底士兵是怎么实现的。我们看看关系图:

Invoker是调用者(司令员),Receiver是被调用者(士兵),MyCommand是命令,实现了Command接口,持有接收对象,看实现代码:

java\] [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain") [copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy") 1. public interface Command { 2. public void exe(); 3. } \[java\] [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain") [copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy") 1. public class MyCommand implements Command { 2. 3. private Receiver receiver; 4. 5. public MyCommand(Receiver receiver) { 6. this.receiver = receiver; 7. } 8. 9. @Override 10. public void exe() { 11. receiver.action(); 12. } 13. } \[java\] [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain") [copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy") 1. public class Receiver { 2. public void action(){ 3. System.out.println("command received!"); 4. } 5. } \[java\] [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain") [copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy") 1. public class Invoker { 2. 3. private Command command; 4. 5. public Invoker(Command command) { 6. this.command = command; 7. } 8. 9. public void action(){ 10. command.exe(); 11. } 12. } \[java\] [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain") [copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy") 1. public class Test { 2. 3. public static void main(String\[\] args) { 4. Receiver receiver = new Receiver(); 5. Command cmd = new MyCommand(receiver); 6. Invoker invoker = new Invoker(cmd); 7. invoker.action(); 8. } 9. } 输出:command received! 这个很哈理解,命令模式的目的就是达到命令的发出者和执行者之间解耦,实现请求和执行分开,熟悉Struts的同学应该知道,Struts其实就是一种将请求和呈现分离的技术,其中必然涉及命令模式的思想!

相关推荐
静水流深_沧海一粟10 小时前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder10 小时前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室17 小时前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦2 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo5 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4965 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃5 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式
驴儿响叮当20105 天前
设计模式之状态模式
设计模式·状态模式
电子科技圈5 天前
XMOS推动智能音频等媒体处理技术从嵌入式系统转向全新边缘计算
人工智能·mcu·物联网·设计模式·音视频·边缘计算·iot
徐先生 @_@|||5 天前
安装依赖三方exe/msi的软件设计模式
设计模式