命令模式是行為模式之一,其中請求作為command 包裝在物件內,並將該物件傳遞給呼叫者,然後呼叫者尋找可以處理此命令的適當物件並將命令傳遞給相應的對象,該對象然後執行該命令。
這也遵循OCP紮實的原則
讓我們以股票市場為例,其中Stock 是一個應該買進或賣出的請求(command),這個Stock 被包裝在Order 下,然後這個Order 被送到經紀人( Invoker ),然後經紀商分析訂單以確定這是BuyOrder還是SellOrder,最後執行買入或賣出訂單(執行命令/請求)
庫存(請求)
public class Stock { private String name ; private int quantity; public Stock(String n, int q){ this.name = n; this.quantity = q; } public void sell(){ System.out.println("[Sell order of quantity " quantity " for stock " name " has been performed]"); } public void buy(){ System.out.println("[Buy order of quantity " quantity " for stock " name " has been performed]"); } }
順序(作為命令包裝在物件內的請求)
public interface Order { public void execute(); }
具體訂單
public class BuyOrder implements Order { private Stock stock; public BuyOrder(Stock s){ this.stock = s; } @Override public void execute(){ stock.buy(); } } public class SellOrder implements Order { private Stock stock; public SellOrder(Stock s){ this.stock = s; } @Override public void execute(){ stock.sell(); } }
經紀商(選擇可以處理命令/訂單的適當物件的呼叫者)
import java.util.ArrayList; import java.util.List; public class Broker { Listorders; public Broker(){ orders = new ArrayList(); } public void addOrder(Order e){ orders.add(e); } public void placeOrder(){ for(Order e : orders){ e.execute(); } orders.clear();// once all the orders are placed by the broker then, the list should be emptied } }
主要的
public class Main { public static void main(String args[]){ //requests Stock stock = new Stock("TCS",20); Stock stock2 = new Stock("Infy",10); //requests wrapped inside object(order) as commands Order order1 = new BuyOrder(stock); Order order2 = new SellOrder(stock2); //order is sent to the broker Broker broker = new Broker(); broker.addOrder(order1); broker.addOrder(order2); //broker at runtime decides the appropriate Object for the reference Order //in other words the invokers decide which object is appropriate and can handle this command/Order broker.placeOrder(); } }
輸出:
[Buy order of quantity 20 for stock TCS has been performed] [Sell order of quantity 10 for stock Infy has been performed]
此模式的要點
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3