命令模式将请求以命令的形式包裹在对象中,然后传递给调用者,调用者寻找处理该命令的对象,并执行命令。
真正的命令执行对象
Stock
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接口
public interface Order { public void execute(); }
Command接口的实现者,用来执行具体的命令。
BuyStock
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(); } }
SellStock
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(); } }
命令的请求者,是命令模式中最重要的角色。这个角色用来对各个命令进行控制。
Broker
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]
参考资料:
https://www.runoob.com/design-pattern/command-pattern.html