概念
命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。
设计
其实就是把“动作”和“命令”两个概念分开
我们之前的写法,都是直接从对象里面调它的方法,比如从Clothes类里调BuyClothes方法,这时候我们其实忽略了“命令”这一层。而命令其实就是用户调用方法这中间的一层。
命令模式把这一层突出了出来,对于“用户的调用”,我们把它抽象为“命令”,存入集合,统一管理,统一执行,统一删除。
代码
public interface Order {
void execute();
}
public class Clothes {
private Logger logger = LoggerFactory.getLogger("Clothes");
public Clothes(int quantity, long price) {
this.quantity = quantity;
this.price = price;
}
private int quantity;
private long price;
public void buy(int quantity, long price) {
logger.info("购买衣服数量:{},价格:{}", quantity, price);
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public long getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
}
public class BuyClothes implements Order{
private Clothes clothes;
public BuyClothes(Clothes clothes) {
this.clothes = clothes;
}
@Override
public void execute() {
this.clothes.buy(clothes.getQuantity(), clothes.getPrice());
}
}
public class Broker {
private static final List<Order> buyClothesList = new ArrayList<>();
// add orders into buyClothesList
public static void takeOrder(Order... orders){
buyClothesList.addAll(Arrays.asList(orders));
}
// execute orders in buyClothesList and clear them
public static void executeOrder(){
for(Order order : buyClothesList){
order.execute();
}
buyClothesList.clear();
}
}
public class MainCommandPattern {
public static void main(String[] args) {
// prepare orders
BuyClothes buyClothes1 = new BuyClothes(new Clothes(1, 1000L));
BuyClothes buyClothes2 = new BuyClothes(new Clothes(2, 3000L));
// take orders into broker
Broker.takeOrder(buyClothes1, buyClothes2);
// execute orders
Broker.executeOrder();
// result:
//14:20:11.750 [main] INFO Clothes - 购买衣服数量:1,价格:1000
//14:20:11.757 [main] INFO Clothes - 购买衣服数量:2,价格:3000
}
}
这里我们用broker作为管理“命令”的中间件,类似于RocketMq的设计。