Command pattern is a data driven design pattern and falls under behavioral pattern category. A request is wrapped under an object as command and passed to invoker object. Invoker object looks for the appropriate object which can handle this command and passes the command to the corresponding object which executes the command.
将一个请求封装成一个对象(command),并且传给invoker对象.
Invoker对象找到可以handle这个请求(command)的合适对象,并将command传递给它来执行。
解除发送者和接收者之间的耦合。
类图:
command pattern
command: 抽象的命令类/接口
concreteCommand:具体的实现类
receiver:该命令的接收者
invoker: 调用该命令的对象
时序图:
时序图
- create the receiver and concreteCommand, send the receiver to concrete command.
- create the Invoker and pass the command to the invoker
- at some time, ask to execute the command. (not call command directly, but use invoker.call(command))
案例:stock
- 新建一个command接口
Order (interface)
public interface Order{
void execute();
}
- 一个receiver类 (也就是command作用的类)
Stock.java
public class Stock{
private String name="ABC";
private int quantity=10;
public void buy(){
System.out.println("Stock [ Name: "+name+",
Quantity: "+quantity+" ] bought");}
public void sell(){
System.out.println("Stock [ Name: "+name+",
Quantity: "+quantity+" ] sold");}
}
3.具体的command类
BuyStock.java
public class BuyStock implements Order{
private Stock abcStock;
public BuyStock(Stock abcStock){
this.abcStock=abcStock;
}
public void execute(){
abcStock.buy();
}
}
SellStokc.java (略)
- 调用command的类
Broker.java
import java.util.ArrayList;
import java.util.List;
public class Broker{
private List orderList = new ArrayList();
public void takeOrder(Orderorder){
orderList.add(order);
}
public void placeOrders(){
for(Order order : orderList){
order.execute();
}
orderList.clear();
}
}
- client类
Demo.java
public class Demo{
public static void main(String[]args{
Stock abcStock = new Stock();
BuyStock buyStockOrder = new BuyStock(abcStock);
SellStock sellStockOrder = new SellStock(abcStock);
Brokerbroker = new Broker();
broker.takeOrder(buyStockOrder);
broker.takeOrder(sellStockOrder);
broker.placeOrders();
}
}