命令模式 -- 设计模式
命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。
思考: 由Broker来接收命令和执行命令, 客户端只负责构造命令, 这里比较简单
package day0321.CommandPattern; import java.util.ArrayList; import java.util.List; public class Demo{ public static void main(String[] args){ Stock stock = new Stock("万科基金", 200); Stock alistock = new Stock("阿里基金", 546); Stock east = new Stock("东方财富网", 500); Stock orderedSameColor = new Stock("同花顺", 500); Stock cn = new Stock("中信证券", 500); // 找到一个代理 Broker broker = new Broker(); // 添加一些命令 broker.takeOrder(new SellStock(alistock)); broker.takeOrder(new SellStock(east)); broker.takeOrder(new SellStock(orderedSameColor)); broker.takeOrder(new SellStock(cn)); broker.takeOrder(new BuyStock(stock)); broker.placeOrder(); } } interface Order{ void execute(); } class Stock{ String name = "ABC"; int quantity = 10; public Stock(String name, int quantity){ this.name = name; this.quantity = quantity; } public Stock(){ } 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 buy(){ String template = "Bought %d %s Stocks%n"; System.out.printf(template, quantity, name); } public void sell(){ String template = "Sold %d %s Stocks%n"; System.out.printf(template, quantity, name); } } // Order class BuyStock implements Order{ Stock stock; public BuyStock(Stock stock){ this.stock = stock; } @Override public void execute(){ stock.buy(); } } // Order class SellStock implements Order{ Stock stock; public SellStock(Stock stock){ this.stock = stock; } @Override public void execute(){ stock.sell(); } } class Broker{ List<Order> orders = new ArrayList<>(); public void takeOrder(Order order){ orders.add(order); } public void placeOrder(){ for (Order order : orders) { order.execute(); } // 执行完之后就清空命令 orders.clear(); } }