设计模式学习02----之命令模式
2018-03-28 07:12
411 查看
今天接着来学习设计模式,还是依照源码用到的来学习。 命令模式作为一种常用的设计模式,让我们一起来揭开其面纱。
从类图中我们可以看出有如下三种角色:
1. Receiver角色(接收者角色):该角色就是干活的角色,命令传递到这儿应该被执行。
2. Invoker 角色(调用者角色):接收到命令,并传递命令。
3. Command角色(命令角色):需要执行的所有命令都在这里。
以下是一个demo
Command 类
ConcreteCommand 类
Invoker 类
Receiver类
client 类
https://blog.csdn.net/zdsicecoco/article/details/51332440
1.
引言
典型的餐厅运作模式就是一个命令模式,顾客下单之后,服务员接收到订单之后,将订单传递给后厨,厨师按照订单内容做菜。定义与结构
命令模式:将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。类图
从类图中我们可以看出有如下三种角色:
1. Receiver角色(接收者角色):该角色就是干活的角色,命令传递到这儿应该被执行。
2. Invoker 角色(调用者角色):接收到命令,并传递命令。
3. Command角色(命令角色):需要执行的所有命令都在这里。
以下是一个demo
Command 类
public abstract class Command { protected Receiver receiver; public Command(Receiver receiver) { this.receiver = receiver; } public abstract void excute(); }
ConcreteCommand 类
public class ConcreteCommand extends Command { public ConcreteCommand(Receiver receiver) { super(receiver); } public void excute() { super.receiver.action(); }; }
Invoker 类
public class Invoker { private Command command; public void setCommand(Command command) { this.command = command; } public void executeCommand() { command.excute(); } }
Receiver类
public class Receiver { public void action() { System.out.println("执行请求"); } }
client 类
public class Client { public static void main(String[] args) { Receiver receiver = new Receiver(); Command command=new ConcreteCommand(receiver); Invoker invoker=new Invoker(); invoker.setCommand(command); invoker.executeCommand(); } }
应用场景
可以参考https://blog.csdn.net/zdsicecoco/article/details/51332440
在junit中的实际应用
在junit中也用到了命令模式。其中,
1.
Test类充当了抽象命令角色
public interface Test { /** * Runs a test and collects its result in a TestResult instance. */ public abstract void run(TestResult result); }
TestCase类和
TestSuite类充当了具体命令角色
public abstract class TestCase extends Assert implements Test { /** * Runs the test case and collects the results in TestResult. */ public void run(TestResult result) { result.run(this); } }
TestResult类充当了调用者角色
/** * Runs a TestCase. */ protected void run(final TestCase test) { startTest(test); Protectable p= new Protectable() { public void protect() throws Throwable { test.runBare(); } }; runProtected(test, p); endTest(test); }
引用
https://www.cnblogs.com/f-zhao/p/6203208.html相关文章推荐
- 设计模式C++学习笔记之十二(Command命令模式)
- 【设计模式】学习笔记8:命令模式
- 【学习笔记】设计模式-命令模式
- 设计模式学习总结:命令模式(Command)
- PureMVC学习系列-从源码深度剖析PureMVC(从PureMVC中看设计模式-Command命令模式) .
- 设计模式学习笔记(19)——命令模式
- 学习笔记:java设计模式--命令模式
- java 设计模式学习笔记十二 command命令设计模式
- 设计模式学习--命令模式
- 设计模式学习(十二)职责链模式-命令模式-解释器模式
- 【设计模式】学习笔记8:命令模式(Command)
- 设计模式学习--命令模式(command)
- headfast设计模式学习笔记02 装饰者
- 命令模式 - 设计模式学习
- 【学习笔记javascript设计模式与开发实践(命令模式)----9】
- 【转】设计模式学习笔记之命令模式
- 设计模式C++学习笔记之十二(Command命令模式)
- java 设计模式学习笔记十二 command命令设计模式
- 学习笔记:Java设计模式-命令模式
- 设计模式C++学习笔记之十二(Command命令模式)