定义:
命令模式把一个请求或者操作封装到一个对象中。命令模式允许系统使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能。
每一个命令都是一个操作:请求的一方发出请求要求执行一个操作;接收的一方收到请求,并执行操作。请求者不必知道命令要发送到哪里去,更不必知道命令是否被执行以及如何执行。接受者不必知道命令从哪里来,只需要执行相应的命令。
四个角色:
请求者:负责调用命令方法执行请求。
接受者:负责执行一个命令请求。
抽象命令:命令接口。
具体命令:命令实现。
// 接收者
public class Recipient {
public void action(){
System.out.println("执行命令操作");
}
}
-----------------------------------------------------------------------------------
// 抽象命令
public interface Command {
void execute();
}
// 具体命令
public class ConcreteCommand implements Command {
private Recipient recipient; // 接受者对象
public ConcreteCommand(Recipient recipient){
this.recipient = recipient;
}
@Override
public void execute(){
recipient.action();
}
}
-----------------------------------------------------------------------------------
// 请求者
public class Requester {
private Command command; // 命令对象
public Requester(Command command){
this.command = command;
}
public void action(){
command.execute();
}
}
// 客户端
public class Client {
public static void main(String[] args){
Recipient recipient = new Recipient(); // 接受者
Command command = new ConcreteCommand(recipient); //命令
Requester requester = new Requester(command); // 请求者
requester.action(); // 发出命令
}
}
Output:
执行命令操作
网友评论