描述
将请求以命令的格式包裹到对象中,并传给调用对象,调用对象寻找可以处理该命令的合适对象,由该合适对象执行。
实例
菜鸟教程上的一个很简单的例子:
假设有个股票类(Stock),对他存在两种操作:买(buystock)和抛(sellstock),先在股票类中定义两个方法:买方法和抛方法,然后定义一个order接口,定义一个默认方法,新建两个类(买和抛)实现这个接口,在这两个类中创建私有的股票对象,默认方法中分别实现股票类的买方法和抛方法。现在我们创建一个中间人,这个中间人有一个order的列表,我们就可以给中间人提供一个添加对股票操作命令的函数,添加到orker列表中。
代码如下:
//创建一个命令接口 public interface Order { void execute(); } //创建一个股票类 public 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"); } } //创建实现两个order的接口的实体类 public class BuyStock implements Order { private Stock abcStock; public BuyStock(Stock abcStock){ this.abcStock = abcStock; } public void execute() { abcStock.buy(); } } public class SellStock implements Order { private Stock abcStock; public SellStock(Stock abcStock){ this.abcStock = abcStock; } public void execute() { abcStock.sell(); } } //创建中间人类 import java.util.ArrayList; import java.util.List; public 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(); } } //主函数 public class CommandPatternDemo { 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(); } }
输出:
Stock [ Name: ABC, Quantity: 10 ] bought Stock [ Name: ABC, Quantity: 10 ] sold
代码来源: 特别感谢 菜鸟教程java之命令模式