设计模式(十)—— 观察者模式

Spring中的观察者模式

Spring实现发布-订阅的例子

定义一个事件

public class DemoEvent extends ApplicationEvent {

    private String message;

    public DemoEvent(Object source) {
        super(source);
    }

    public DemoEvent(Object source, String message) {
        super(source);
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

}


定义一个对该事件的监听者A



@Component
public class DemoListener implements ApplicationListener<DemoEvent> {

    private static final Logger LOGGER = LogManager.getLogger(ExternalProxyServiceImpl.class);


    @Override
    public void onApplicationEvent(DemoEvent event) {
        String msg = event.getMessage();

        LOGGER.info("我是蘑菇头,接收到的信息:" + msg);
    }


}

定义一个对该事件的监听者B


@Component
public class Demo2Listener implements ApplicationListener<DemoEvent> {

    private static final Logger LOGGER = LogManager.getLogger(ExternalProxyServiceImpl.class);


    @Override
    public void onApplicationEvent(DemoEvent event) {
        String msg = event.getMessage();

        LOGGER.info("我是熊猫头,接收到的信息:" + msg);
    }

}



定义一个发布者


@Component
public class DemoPublisher {


    @Autowired
    ApplicationContext applicationContext;

    public void publish(String message) {
        applicationContext.publishEvent(new DemoEvent(this,message));
    }


}



单元测试,测试结果


@SpringBootTest
@RunWith(SpringRunner.class)
public class EventTest {

    @Autowired
    private DemoPublisher demoPublisher;

    @Test
    public void test(){

        demoPublisher.publish("观察者模式");

    }


}



源码分析

事件监听者


public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
    void onApplicationEvent(E var1);
}

事件发布者


@FunctionalInterface
public interface ApplicationEventPublisher {
    default void publishEvent(ApplicationEvent event) {
        this.publishEvent((Object)event);
    }

    void publishEvent(Object var1);
}




zookeeper中的观察者模式

参考文档

[1]: 面试官:“谈谈Spring中都用到了那些设计模式?”

posted @ 2016-11-21 18:25  清泉白石  阅读(245)  评论(0编辑  收藏  举报