意图:将一个请求封装成一个对象,从而使您可以用不同的请求对客户进行参数化。
主要解决:在软件系统中,行为请求者与行为实现者通常是一种紧耦合的关系,但某些场合,比如需要对行为进行记录、撤销或重做、事务等处理时,这种无法抵御变化的紧耦合的设计就不太合适。
何时使用:在某些场合,比如要对行为进行"记录、撤销/重做、事务"等处理,这种无法抵御变化的紧耦合是不合适的。在这种情况下,如何将"行为请求者"与"行为实现者"解耦?将一组行为抽象为对象,可以实现二者之间的松耦合。
如何解决:通过调用者调用接受者执行命令,顺序:调用者→接受者→命令。
关键代码:定义三个角色:1、received 真正的命令执行对象 2、Command 3、invoker 使用命令对象的入口
package DesignPattern.CommandPattern;
public interface Order {
public void execute();
}
package DesignPattern.CommandPattern;
public class SellStock implements Order{
private Stock abcStock;
public SellStock(Stock abcStock) {
this.abcStock = abcStock;
}
public void execute() {
abcStock.sell();
}
}
package DesignPattern.CommandPattern;
public class BuyStock implements Order{
private Stock abcStock;
public BuyStock(Stock abcStock){
this.abcStock = abcStock;
}
public void execute() {
abcStock.buy();
}
}
package DesignPattern.CommandPattern;
import java.util.List;
import java.util.ArrayList;
public class Broker {
private List<Order> orderList = new ArrayList<>();
public void takeOrder(Order order){
orderList.add(order);
}
public void placeOrders(){
for (Order order : orderList) {
order.execute();
}
orderList.clear();
}
}
package DesignPattern.CommandPattern;
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 ");
}
}
package DesignPattern.CommandPattern;
public class Client {
public static void main(String[] args) {
Stock abcStock = new Stock();
BuyStock buyStockOrder = new BuyStock(abcStock);
SellStock sellStockOrder = new SellStock(abcStock);
Broker broker = new Broker();
broker.takeOrder(buyStockOrder);
broker.takeOrder(sellStockOrder);
broker.placeOrders();
}
}