命令模式
GuoJun 2022-05-16 设计模式
# 简介
命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。
# 实现
- 创建一个命令接口
public interface Order {
void execute();
}
- 创建一个请求类
public class Stock {
private String name = "ABC";
private int quantity = 10;
public void buy(){
System.out.println("购买 [名称: " + name + ", 数量: " + quantity + "]");
}
public void sell(){
System.out.println("卖出 [名称: " + name + ", 数量: " + quantity + "]");
}
}
- 创建实现了Order接口的实体类
public class BuyStock implements Order {
private Stock absStock;
public BuyStock(Stock absStock) {
this.absStock = absStock;
}
@Override
public void execute() {
absStock.buy();
}
}
public class SellStock implements Order {
private Stock absStock;
public SellStock(Stock absStock) {
this.absStock = absStock;
}
@Override
public void execute() {
absStock.sell();
}
}
- 创建命令调用类
public class Broker {
private List<Order> orderList = new ArrayList<>();
public void takeOrder(Order order){
orderList.add(order);
}
public void placeOrders(){
for (Order order : orderList) {
order.execute();
}
orderList.clear();
}
}
- 使用broker类来接受并执行命令
public class CommandPatternDemo {
public static void main(String[] args) {
Stock stock = new Stock();
BuyStock buyStockOrder = new BuyStock(stock);
SellStock sellStockOrder = new SellStock(stock);
Broker broker = new Broker();
broker.takeOrder(buyStockOrder);
broker.takeOrder(sellStockOrder);
broker.placeOrders();
}
}