设计模式(二) --- 使用监听驱动实现观察者模式

一、实现观察者模式:

  1、继承 ApplicationEvent 类, 定义需要发布的事件类;

  2、实现 ApplicationListener 接口(或者使用 @EventListener)监听事件;

  3、使用 ApplicationEventPublisher 发布定义的事件类

 

二、实现

1、继承 ApplicationEvent 类, 定义需要发布的事件类;

      定义订单事件

public class OrderEvent extends ApplicationEvent {
    public OrderEvent(Object source) {
        super(source);
    }
}

  

 

2、实现 ApplicationListener 接口(或者使用 @EventListener)监听事件;

2.1、发微信

// 订单事件的监听器
@Component // 交给spring托管
public class WxListener implements ApplicationListener<OrderEvent> {
    @Override
    public void onApplicationEvent(OrderEvent event) {
        // 3 --- 发送微信通知 ----
        System.out.println("3. 发送微信消息");
    }
}

2.2、发短信

// 订单事件的监听器
@Component // 交给spring托管 -- 创建对象并且保留在IOC容器
public class SmsListener implements ApplicationListener<OrderEvent> {
    @Override
    public void onApplicationEvent(OrderEvent event) {
        // 2 --- 发送短信 --- TODO 此处省略短信接口调用的N行代码
        System.out.println("2、 短信发送成功");
    }
}

 

3、定义发布类

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.jm.listener.event.OrderEvent;

@Component
public class MyPublisher implements ApplicationContextAware {

	private ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	public void publisherEvent(OrderEvent orderEvent) {
		System.out.println("---开始发布 orderEvent 事件---");
		applicationContext.publishEvent(orderEvent);
	}

}

  

测试:

在 service 中使用

@Service
public class TestServiceImpl implements TestService {

	@Autowired
    private MyPublisher myPublisher;
	
	@Override
	public boolean test() {

		System.out.println("============send message test=============");
		OrderEvent orderEvent = new OrderEvent("参数");
		myPublisher.publisherEvent(orderEvent);
		return true;
	}

}

  

github: https://github.com/szjomin/observerPattern

 

 ----------------------------------------------------

参考:https://www.cnblogs.com/jmcui/p/11054756.html

 

 

 

 

 

 

 

 

 

  

posted @ 2020-06-04 23:56  李荣先辈Java  阅读(239)  评论(0编辑  收藏  举报