命令模式,将一个请求封装为一个对象(命令),使发出请求的责任和执行请求的责任分割开,有效降低系统的耦合度。这样两者之间通过命令对象进行沟通,这样方便将命令对象进行储存、传递、调用、增加与管理。命令模式包含以下主要角色:
UML设计图如下:
1)Command 接口:
public interface Command {
void exe(String command);
}
?2)命令的接收和执行者类Receiver:
@Slf4j
public class Receiver {
public void action(String commandMsg) {
log.info("received command and execute command ...");
}
}
3)Command 接口的实现类 ConcreteCommand:
public class ConcreteCommand implements Command {
private Receiver receiver;
public ConcreteCommand(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void exe(String command) {
receiver.action(command);
}
}
4)命令调用者类 Invoker:
@Slf4j
public class Invoker {
private Command command;
public Invoker(Command command) {
this.command = command;
}
public void action(String commandMsg) {
log.info("command sending ...");
command.exe(commandMsg);
}
}
5)测试命令模式:
public class CommandTest {
public static void main(String[] args) {
// 定义命令的接收者和执行者
Receiver receiver = new Receiver();
// 命令实现者
ConcreteCommand command = new ConcreteCommand(receiver);
// 定义命令调用者
Invoker invoker = new Invoker(command);
// 调用命令
invoker.action("cmd");
}
}
打印结果: