实例
我们创建了一个充当订单的接口Order。我们创建了一个Stock类作为请求。我们有一些具体的订单类BuyStock和SellStock实现了Order接口,这些接口将执行实际的订单处理。创建一个类Broker,该类充当调用者对象。它可以接受和下订单。
Broker对象使用订单模式来根据订单的类型识别哪个对象将执行哪个订单。我们的演示类CommandPatternDemo将使用Broker类来演示订单模式。
第1步 创建一个订单接口。Order.java
public interface Order {
void execute();
}
第2步 - 创建一个请求类。Stock.java
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");
}
}
第3步 - 创建实现Order接口的具体类。BuyStock.java , SellStock.java
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();
}
}
步骤4 - 创建订单调用程序类。 Broker.java
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();
}
}
第5步 - 使用Broker类接收和执行订单。 CommandPatternDemo.java
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();
}
}
第6步 - 验证输出。
Stock [ Name: ABC, Quantity: 10 ] bought
Stock [ Name: ABC, Quantity: 10 ] sold