概念
将一个请求封装成一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
使用命令模式可以将命令的执行者和请求者解耦。
代码
执行者
public class Executor {
public void appointedToBegForFood () {
System.out.println("孙悟空被派去化缘");
}
public void appointedToExplore(){
System.out.println("孙悟空被派去探路");
}
}
抽象命令
public abstract class Command {
protected Executor executor;
public Command(Executor executor) {
this.executor = executor;
}
public void setExecutor(Executor executor) {
this.executor = executor;
}
public abstract void executeCommand () ;
}
具体命令一
public class BegFoodCommand extends Command {
public BegFoodCommand(Executor executor) {
super(executor);
}
@Override
public void executeCommand() {
this.executor.appointedToBegForFood();
}
}
具体命令二
public class ExploreCommand extends Command {
public ExploreCommand(Executor executor) {
super(executor);
}
@Override
public void executeCommand() {
this.executor.appointedToExplore();
}
}
请求者
public class Ivoker {
private Command command;
public void setCommand(Command command){
this.command = command;
}
public void notifyExecutor() {
command.executeCommand();
}
}
客户端
public class Client {
public static void main(String[] args) {
Executor sunWukong = new Executor();
Ivoker tangXuanzang = new Ivoker();
Command begFoodCommand = new BegFoodCommand(sunWukong);
Command exploreCommand = new ExploreCommand(sunWukong);
tangXuanzang.setCommand(begFoodCommand);
tangXuanzang.notifyExecutor();
tangXuanzang.setCommand(exploreCommand);
tangXuanzang.notifyExecutor();
}
}
// 孙悟空被派去化缘
// 孙悟空被派去探路
特点
使用命令模式可以将命令的执行者和请求者解耦,同时方便添加新的命令。但是命令模式支持可撤销的操作是如何实现的。