命令模式是行为模式之一,其中请求作为 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