【设计模式】观察者模式

      观察者模式,又称发布订阅
以保存订单完成后,通知仓库系统发货为例:

订单类:

public class Order {

    /**
     * 订单编号
     */
    private String orderCode;
    /**
     * 商品编号
     */
    private String productNum;
    /**
     * 数量
     */
    private int quantity;

    public String getOrderCode() {
        return orderCode;
    }

    public void setOrderCode(String orderCode) {
        this.orderCode = orderCode;
    }

    public String getProductNum() {
        return productNum;
    }

    public void setProductNum(String productNum) {
        this.productNum = productNum;
    }

    public int getQuantity() {
        return quantity;
    }

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

订单服务:

public interface OrderService {
    void saveOrder(Order order);
}

订单服务实现类:


@Component("orderService")
public class OrderServiceImpl implements OrderService {
    @Autowired
    ApplicationContext applicationContext;

    public void saveOrder(Order order) {
        System.out.println("保存订单信息");
        //发布订单保存完成的通知
        applicationContext.publishEvent(new OrderEvent(this,order));
    }
}

 订单事件:

/**
 * 订单事件
 */
public class OrderEvent extends ApplicationEvent{
    private Order order;

    public OrderEvent(Object source,Order order) {
        super(source);
        this.order = order;
    }

    public Order getOrder() {
        return order;
    }
}

订单事件监听器:

/**
 * 仓库系统对订单事件的监听器
 */
@Component
public class WarehouseListener implements ApplicationListener<OrderEvent> {

    public void onApplicationEvent(OrderEvent orderEvent) {
        Order order = orderEvent.getOrder();
        System.out.println(order.getOrderCode()+"的商品:"+order.getProductNum()+"数量:"+order.getQuantity()+"已发货");

    }
}

demo:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application.xml")
public class OrderDemo {
    @Autowired
    OrderService orderService;

    @Test
    public void placeAnOrder(){
        //模拟保存订单
        Order order = new Order();
        order.setOrderCode("OT_2018091301");
        order.setProductNum("J151232");
        order.setQuantity(1);
        orderService.saveOrder(order);
    }
}

输出结果:
 

保存订单信息
11:26:11,829 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory]:251 - <Returning cached instance of singleton bean 'warehouseListener'>
OT_2018091301的商品:J151232数量:1已发货

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值