观察者模式

观察者模式

定义
定义了对象之间的一对多依赖,让多个观察者监听同一个对象的行为,当该行为发生的时候,则做出一定的动作

接下来以以下场景模拟:天气变化了,则发出提示

天气模型

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Weather {
    private String address;
    private Integer temperature;
    private List<Observer> observers;
    public void addObserver(Observer observer){
        observers.add(observer);
    }
    public void removeObserver(Observer observer){
        observers.remove(observer);
    }
    public void changeTemperature(int temperature){
        this.temperature=temperature;
        // 通知所有的观察者
        for (Observer observer : observers) {
            observer.update(temperature);
        }
    }
}

观察者的接口

public interface Observer {
    void update(Integer temperature);
}

邮件的观察者

public class EmailObserver implements Observer {

    @Override
    public void update(Integer temperature) {
        System.out.println("发邮件告诉用户天气改变了,变为了"+temperature);
    }
}

短信观察者

public class MsgObserver implements Observer{
    @Override
    public void update(Integer temperature) {
        System.out.println("发短信告诉用户气温改变了,变为了"+temperature);
    }
}

SpringBoot的观察者模式的实践

import org.springframework.context.ApplicationEvent;
public class MyEvent extends ApplicationEvent {

    /**
     * Create a new {@code ApplicationEvent}.
     *
     * @param source the object on which the event initially occurred or with
     *               which the event is associated (never {@code null})
     */
    public MyEvent(Object source) {
        super(source);
    }
}
import org.springframework.context.ApplicationListener;
public class MyEventListener implements ApplicationListener<MyEvent> {

    @Override
    public void onApplicationEvent(MyEvent event) {
        System.out.println("处理自定义事件");
    }
}
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
public class MyApplication implements ApplicationEventPublisherAware {
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
    public void doSomething(){
        System.out.println("doSomething");
        applicationEventPublisher.publishEvent(new MyEvent("something"));
    }
}

具体执行流程见观察者模式在spring中的应用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

芝麻\n

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值