您的位置:首页 > 其它

设计模式学习02----之命令模式

2018-03-28 07:12 411 查看
今天接着来学习设计模式,还是依照源码用到的来学习。 命令模式作为一种常用的设计模式,让我们一起来揭开其面纱。

引言

典型的餐厅运作模式就是一个命令模式,顾客下单之后,服务员接收到订单之后,将订单传递给后厨,厨师按照订单内容做菜。

定义与结构

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

类图



从类图中我们可以看出有如下三种角色:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: