1、概念
请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。
2、场景
2.1 :工作流Activit框架中就用到了这种模式,它总共7个接口,每个接口都有特定的命令去执行数据库中的表,因为activit框架会自动生成23张表,所以这些命令都会在这些表中直接增删改查,我们在后台直接调用这些命令就好。
3、简单代码实现
public interface Order { void execute();}
public class Apple { private String name = "ABC"; private int quantity = 10; public void buy(){ System.out.println("买家name="+name+" quantity="+quantity); } public void sell(){ System.out.println("卖家name="+name+" quantity="+quantity); }}
public class BuyApple implements Order { private Apple apple; public BuyApple(Apple apple) { this.apple = apple; } @Override public void execute() { apple.buy(); }}
public class SellApple implements Order { private Apple apple; public SellApple(Apple apple){ this.apple = apple; } @Override public void execute() { apple.sell(); }}
public class Command { private ListorderList = new ArrayList<>(); public void takeOrder(Order order){ orderList.add(order); } public void placeOrders(){ for (Order order : orderList) { order.execute(); } orderList.clear(); }}
main函数执行结果
public class Main { public static void main(String[] args) { Apple apple = new Apple(); BuyApple buyStockOrder = new BuyApple(apple); SellApple sellStockOrder = new SellApple(apple); Command command = new Command(); command.takeOrder(buyStockOrder); command.takeOrder(sellStockOrder); command.placeOrders(); }}