命令模式将一个请求封装成一个对象,从而使您可以用不同的请求对客户进行参数化。命令模式的优点是降低了系统耦合度,新的命令很容易添加到系统中去;缺点是使用命令模式可能会导致某些系统有过多的具体命令类。
public interface Order {
void execute();
}
class Stock {
private String name = "ABC";
private int quantity = 10;
void buy(){
System.out.println("Stock[Name:" + name + ",Quantity:" + quantity + "] bought.");
}
void sell(){
System.out.println("Stock[Name:" + name + ",Quantity:" + quantity + "] sold.");
}
}
/**
* 买入股票指令
*/
public class BuyStock implements Order {
private Stock stock;
BuyStock(Stock stock){
this.stock = stock;
}
@Override
public void execute() {
stock.buy();
}
}
/**
* 卖出股票指令
*/
public class SellStock implements Order {
private Stock stock;
SellStock(Stock stock){
this.stock = stock;
}
@Override
public void execute() {
stock.sell();
}
}
public class Broker {
private List<Order> orders = new ArrayList<>();
void takeOrder(Order order){
orders.add(order);
}
void placeOrders(){
for(Order order:orders){
order.execute();
}
orders.clear();
}
}
public class CommandInstance {
public static void main(String[] args) {
Stock stock = new Stock();
BuyStock buyStockOrder = new BuyStock(stock);
SellStock sellStock = new SellStock(stock);
Broker broker = new Broker();
broker.takeOrder(buyStockOrder);
broker.takeOrder(sellStock);
broker.placeOrders();
}
}