命令设计模式(Command Pattern)
描述: 命令设计模式是一种数据驱动的设计模式,它属于行为模式,请求以命令的方式包裹在对象中,并传递给调用对象,调用对象寻找可以处理改命令的合适对象,并把该命令传递给相应的对象,该对象执行命令。
核心思想: 将一个情求封装为一个对象,从而可以使用不同的请求对客户进行参数化
使用场景: 认为是命令的地方可以使用命令设计模式
命令设计模式的优点:
- 降低系统的耦合
- 新的命令可以很容易的添加到系统中去
命令设计模式是缺点:
- 会导致某些系统过多的具体命名的类,不符合依赖倒置原则
示例:
1 2 3 4 5
| interface Order { void execute(); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Stock { private String name = "ABC"; private int quantity = 10;
public void buy() { System.out.println("Stock [ Name: " + name + " Quantity: " + quantity + " ] bought"); }
public void sell() { System.out.println("Stock [ Name: " + name + " Quantity: " + quantity + " ] sold"); }
|
1 2 3 4 5 6 7 8 9 10 11 12
| class BuyStock implements Order { private Stock abcStock;
public BuyStock(Stock abcStock) { this.abcStock = abcStock; }
@Override public void execute() { abcStock.buy(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| class SellStock implements Order { private Stock abcStock;
public SellStock(Stock abcStock) { this.abcStock = abcStock; }
@Override public void execute() { abcStock.sell(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Broker { private List<Order> orderList = new ArrayList<Order>();
public void takeOrder(Order order) { orderList.add(order); }
public void placeOrders() { for (Order order : orderList) { order.execute(); } orderList.clear(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class Test { public static void main(String[] args) { Stock abcStock = new Stock();
BuyStock buyStockOrder = new BuyStock(abcStock); SellStock sellStockOrder = new SellStock(abcStock);
Broker broker = new Broker(); broker.takeOrder(buyStockOrder); broker.takeOrder(sellStockOrder);
broker.placeOrders(); } }
|