标签:mmc ring interrupt redo get sys new 声明 cut
定义:将一个请求封装为一个对象,使发出的请求的对象和执行请求的对象分割开。这两者之间通过命令对象进行沟通,这样方便将命令对象进行储存、传递、调用、增加与管理。
顺序:请求者->命令->执行者
优点:
命令模式结构:
使用场景:在某些场合,比如要对行为进行“记录、撤销、重做”等处理。或者认为是命令的地方。
示例场景:顾客点了一道菜,点菜这个可以当成是一个命令,顾客是请求者,厨师是接收者。
示例代码:
public interface Command {
void execute();
}
public class FoodCommand implements Command {
private Receiver receiver;
private String foodName;
public FoodCommand(String foodName) {
this.foodName = foodName;
}
public Receiver getReceiver() {
return receiver;
}
public void setReceiver(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
receiver.action(foodName);
}
}
/**
* 顾客类
*/
public class Customer {
private Command command;
public Customer(Command command) {
this.command = command;
}
public void call(){
System.out.println("顾客点菜");
command.execute();
}
}
/**
* 厨师类
*/
public class Receiver {
public void action(String foodName){
System.out.println("厨师开始制作:"+foodName);
}
}
测试代码:
public class ParteenDemo {
public static void main(String[] args) throws InterruptedException, CloneNotSupportedException {
FoodCommand command=new FoodCommand("红烧茄子");
Receiver receiver=new Receiver();
command.setReceiver(receiver);
Customer customer=new Customer(command);
customer.call();
}
}
命令模式还有一种扩展,与组合模式结合,称为组合命令模式。结构如下:
标签:mmc ring interrupt redo get sys new 声明 cut
原文地址:https://www.cnblogs.com/javammc/p/14952412.html