0%

命令模式

描述

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

适用

命令模式的目的就是达到命令的发出者和执行者之间解耦,实现请求和执行分开,熟悉Struts的同学应该知道,Struts其实就是一种将请求和呈现分离的技术,其中必然涉及命令模式的思想

UML

e745a69f67e74a938fa195a731d4f47c

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//接口
interface Command{
public void exe();
}
//定义类
class Receiver{
public void action(){
Test.printMsg("command receive");
}
}
class Invoker{
private Command command;
public Invoker(Command command){
this.command = command;
}
public void action(){
command.exe();
}
}
//实现类
class MyCommand implements Command {
private Receiver receiver;
public MyCommand(Receiver receiver){
this.receiver = receiver;
}
@Override
public void exe(){
receiver.action();
}
}
//测试
public class Test {
public static void printMsg(String msg){
System.out.println(msg);
}
public static void main(String[] args){
Receiver receiver = new Receiver();
Command cmd = new MyCommand(receiver);
Invoker invoker = new Invoker(cmd);
invoker.action();
}
}