JAVA 二十三种设计模式大全(二十)命令模式(Command Pattern)

概念

命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。

设计

请添加图片描述

其实就是把“动作”和“命令”两个概念分开

我们之前的写法,都是直接从对象里面调它的方法,比如从Clothes类里调BuyClothes方法,这时候我们其实忽略了“命令”这一层。而命令其实就是用户调用方法这中间的一层。

命令模式把这一层突出了出来,对于“用户的调用”,我们把它抽象为“命令”,存入集合,统一管理,统一执行,统一删除。

代码

public interface Order {
    void execute();
}
public class Clothes {
    private Logger logger = LoggerFactory.getLogger("Clothes");

    public Clothes(int quantity, long price) {
        this.quantity = quantity;
        this.price = price;
    }

    private int quantity;
    private long price;

    public void buy(int quantity, long price) {
        logger.info("购买衣服数量:{},价格:{}", quantity, price);
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public long getPrice() {
        return price;
    }

    public void setPrice(long price) {
        this.price = price;
    }
}
public class BuyClothes implements Order{
    private Clothes clothes;

    public BuyClothes(Clothes clothes) {
        this.clothes = clothes;
    }

    @Override
    public void execute() {
        this.clothes.buy(clothes.getQuantity(), clothes.getPrice());
    }
}
public class Broker {
    private static final List<Order> buyClothesList = new ArrayList<>();
    // add orders into buyClothesList
    public static void takeOrder(Order... orders){
        buyClothesList.addAll(Arrays.asList(orders));
    }
    // execute orders in buyClothesList and clear them
    public static void executeOrder(){
        for(Order order : buyClothesList){
            order.execute();
        }
        buyClothesList.clear();
    }
}
public class MainCommandPattern {
    public static void main(String[] args) {
        // prepare orders
        BuyClothes buyClothes1 = new BuyClothes(new Clothes(1, 1000L));
        BuyClothes buyClothes2 = new BuyClothes(new Clothes(2, 3000L));
        // take orders into broker
        Broker.takeOrder(buyClothes1, buyClothes2);
        // execute orders
        Broker.executeOrder();
        // result:
        //14:20:11.750 [main] INFO Clothes - 购买衣服数量:1,价格:1000
        //14:20:11.757 [main] INFO Clothes - 购买衣服数量:2,价格:3000

    }
}

这里我们用broker作为管理“命令”的中间件,类似于RocketMq的设计。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值