簡單的說,觀察者模式,就類似於 廣播站發送廣播,和收音機的關系。多個收音機去收聽同一個廣播頻道。 在實際的業務場景中,可以是這樣的。創建訂單成功后,發布事件。然后減庫存。發送短信。調用微信。調用物流服務。等多個后續業務,都去監聽同一個事件。
定義一個事件。
package com.study.design.observer.spring; import org.springframework.context.ApplicationEvent; /** * 定義事件 */ public class OrderEvent extends ApplicationEvent { public OrderEvent(Object source) { super(source); } }
定義事件發布器
package com.study.design.observer.spring; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationEvent; import org.springframework.stereotype.Service; // 事件發布器。把事件發布到 spring容器中。 @Service public class OrderPublish implements ApplicationContextAware { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // 獲取spring容器,設置到私有屬性。 this.applicationContext = applicationContext; } // 調用spring容器 發布事件 public void publishEvent(ApplicationEvent event){ applicationContext.publishEvent(event); } }
訂單服務中,發布事件
package com.study.design.observer.spring; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * 訂單操作,業務偽代碼 */ @Service public class OrderService { // 注入事件發布器 @Autowired private OrderPublish orderPublish; /** * 電商 - 新訂單訂單 */ public void saveOrder() { System.out.println("1、 訂單創建成功"); // 創建事件 ,可以設置參數 OrderEvent orderEvent = new OrderEvent(123456); // 發布事件 orderPublish.publishEvent(orderEvent); } }
發短信 監聽器 服務
package com.study.design.observer.spring; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; // 監聽器 ,有事件發布后,才會執行 @Component public class SmsListener implements ApplicationListener<OrderEvent> { @Override public void onApplicationEvent(OrderEvent event) { // 獲取事件中的參數。 System.out.println("event.getSource的值是:"+event.getSource()); // 2---短信通知 System.out.println("2、 調用短信發送的接口 -> 恭喜喜提羽絨被子"); } }
如此,就可以創建多個監聽器,進行不同的業務處理。這就是觀察者模式。
