今天接着来学习设计模式,还是依照源码用到的来学习。 命令模式作为一种常用的设计模式,让我们一起来揭开其面纱。
引言
典型的餐厅运作模式就是一个命令模式,顾客下单之后,服务员接收到订单之后,将订单传递给后厨,厨师按照订单内容做菜。
定义与结构
命令模式:将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。
类图
从类图中我们可以看出有如下三种角色:
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();
}
}
应用场景
可以参考
在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);
}