命令行把请求和操作封装起来,坦白的讲,我现在还不是特别理解,也没有再具体的项目中使用过,感觉有点过于复杂。
本文参考一些材料,给出一个简单的例子。如下:
- Trade
public class Trade { public void doSell(){ System.out.println("doSell"); } public void doBuy(){ System.out.println("doBuy"); } }
- TradeCommand
public abstract class TradeCommand { protected Trade trade; public TradeCommand(Trade trade){ this.trade = trade; } public abstract void execute(); }
- BuyTradeCommand
public class BuyTradeCommand extends TradeCommand { public BuyTradeCommand(Trade trade) { super(trade); } @Override public void execute() { this.trade.doBuy(); } }
- SellTradeCommand
public class SellTradeCommand extends TradeCommand { public SellTradeCommand(Trade trade) { super(trade); } @Override public void execute() { this.trade.doSell(); } }
- Invoke
public class Invoke { public TradeCommand command; public void setCommand(TradeCommand command){ this.command = command; } public void execute(){ command.execute(); } }
- APP 测试类
public class App { public static void main(String[] args) { Trade trade = new Trade(); Invoke invoke = new Invoke(); invoke.setCommand(new SellTradeCommand(trade)); invoke.execute(); invoke.setCommand(new BuyTradeCommand(trade)); invoke.execute(); } }