行为型(九) - 命令模式

一、概念

命令模式(Command Pattern):请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。

二、实现

这里借鉴菜鸟教程的例子,一个经纪人处理股票买卖订单的过程。
1、股票抽象类及实现类

#Stoke 
public abstract class Stoke {
    protected String name;
    protected int price;

    public Stoke(String name, int price) {
        this.name = name;
        this.price = price;
    }

    public void buy() {
        System.out.println("买" + name + "股票" + "| 价格" + price);
    }

    public void sell(){
        System.out.println("卖" + name + "股票" + "| 价格" + price);
    }
}

#MedicineStoke 
public class MedicineStoke extends Stoke {
    public MedicineStoke(String name, int price) {
        super(name, price);
    }
}

2、订单

public interface Order {
    void execute();
}

public class BuyOrder implements Order {
    private Stoke stoke;

    public BuyOrder(Stoke stoke){
        this.stoke = stoke;
    }

    @Override
    public void execute() {
        stoke.buy();
    }
}

public class SellOrder implements Order {
    private Stoke stoke;

    public SellOrder(Stoke stoke) {
        this.stoke = stoke;
    }

    @Override
    public void execute() {
        stoke.sell();
    }
}

3、经纪人,可处理股票订单

public class Broker {
    private List<Order> orderList = new ArrayList<Order>();
    public void takeOrder(Order order) {
        orderList.add(order);
    }

    public void processOrder() {
        for (Order order : orderList) {
            order.execute();
        }
        orderList.clear();
    }
}

4、测试类

public class Client {
    public static void main(String[] args) {
        MedicineStoke medicineStoke = new MedicineStoke("中欧医疗", 20);
        BuyOrder buyOrder = new BuyOrder(medicineStoke);
        SellOrder sellOrder = new SellOrder(medicineStoke);

        Broker broker = new Broker();
        broker.takeOrder(buyOrder);
        broker.takeOrder(sellOrder);
        broker.processOrder();
    }
}

5、运行结果
命令模式结果.png

你可能感兴趣的:(设计模式,命令模式)