Java21观察者模式

也可被称为发布-订阅模式
通过观察者模式可以定义一对多的依赖关系,可以让多个观察者监听某个主体对象(被观察者)。等主题对象状态发生变化,会主动通知所有的观察者。

观察者模式第一步:新建接口

package com.javawu.observer;

public interface Notify {
    //通知方法
    public void notified(String weather);
}

观察者模式第二步:观察者实现接口

package com.javawu.observer;
//相当于学生订阅天气预报
//相当于观察者
public class Student implements Notify {
    public void notified(String weather) {
        System.out.println(weather);
    }
}

观察者模式第三步:主体对象(被观察者)

package com.javawu.observer;
import java.util.ArrayList;
import java.util.List;
//相当于主体对象,被观察者
public class Station{
    //用来存放观察者
    List<Notify> list = new ArrayList<>();
    public void addObserver(Notify notify) {
        if(!list.contains(notify)) {
            list.add(notify);
        }
    }
    //删除观察者
    public void removeObserver(Notify notify) {
        if(list.contains(notify)) {
            list.remove(notify);
        }
    }
    //通知观察者
    public void notifyObserver() {
        for (Notify notify : list) {
            notify.notified("暴雨:适合晨练");
        }
    }
}

观察者模式的使用

package com.javawu.observer;
public class Demo1 {
    public static void main(String[] args) {
        Station station = new Station();
        Student student = new Student();
        Student student2 = new Student();
        //添加观察者
        station.addObserver(student);
        station.addObserver(student2);
        //通知观察者
        station.notifyObserver();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容