命令模式將請求以命令的形式包裹在對象中,而後傳遞給調用者,調用者尋找處理該命令的對象,並執行命令。html
真正的命令執行對象 java
Stockide
public class Stock { private String name = "ABC"; private int quantity = 10; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public void buyStock() { System.out.println("BuyStock [name=" + name + ", quantity=" + quantity + "]"); } public void sellStock() { System.out.println("SellStock [name=" + name + ", quantity=" + quantity + "]"); } }
Command接口this
public interface Order { public void execute(); }
Command接口的實現者,用來執行具體的命令。spa
BuyStock code
public class BuyStock implements Order{ private Stock abcStock; public BuyStock(Stock abcStock) { super(); this.abcStock = abcStock; } @Override public void execute() { // TODO Auto-generated method stub abcStock.buyStock(); } }
SellStockhtm
public class SellStock implements Order{ private Stock abcStock; public SellStock(Stock abcStock) { super(); this.abcStock = abcStock; } @Override public void execute() { // TODO Auto-generated method stub abcStock.sellStock(); } }
命令的請求者,是命令模式中最重要的角色。這個角色用來對各個命令進行控制。對象
Brokerblog
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 placeOrderList() { for(Order order: orderList) { order.execute(); } orderList.clear(); } }
Main接口
public class Main { public static void main(String[] args) { Stock abc = new Stock(); Order buyAbc = new BuyStock(abc); Order sellAbc = new SellStock(abc); Broker broker = new Broker(); broker.takeOrder(buyAbc); broker.takeOrder(sellAbc); broker.placeOrderList(); } }
運行結果:
BuyStock [name=ABC, quantity=10] SellStock [name=ABC, quantity=10]
參考資料: