设计模式之观察者模式

设计模式之观察者模式

观察者模式(Observer) 定义对象间的一种一对多的依赖关系,以便当一个对象的状态发生改变时,所有依赖它的对象都得到通知并自动刷新。又称发布-订阅模式。


需求:实现天气预报的功能。当我们使用一个天气预报APP时,每当有天气变化时,就会发出通知给我们,以便我们作出相应的改变。比如预报通知今天下雨,我就带一把雨伞出门。


首先,观察者接口(用户):

/**
 * 观察者接口,对天气变化作出响应
 */
public interface IWeatherObserver {

    void upDate(String weather);
}

学生用户:

/**
 * 具体的观察者,当通知者发来消息时,作出相应的改变。
 */
public class Student implements IWeatherObserver {
    String name;

    public Student(String name) {
        this.name = name;
    }

    @Override
    public void upDate(String weather) {
        if ("晴天".equals(weather)) {
            System.out.println(name + "高高兴兴去上学!!");
        } else if ("雾霾".equals(weather)) {
            System.out.println(name + "多吸两口去上学!");
        } else if ("刮风".equals(weather)) {
            System.out.println(name + "在家睡觉!");
        } else if ("冰雹".equals(weather)) {
            System.out.println(name + "在家睡觉 !");
        } else if ("下雪".equals(weather)) {
            System.out.println(name + "等下完再去上学!");
        }

    }
}

工人用户:

public class Emp implements IWeatherObserver {

    String name;

    public Emp(String name) {
        this.name = name;
    }

    @Override
    public void upDate(String weather) {
        if("晴天".equals(weather)){
            System.out.println(name+"高高兴兴的去上班!!");
        }else if("雾霾".equals(weather)){
            System.out.println(name+"戴着消毒面具去上班!");
        }else if("刮风".equals(weather)){
            System.out.println(name+"拖着大石头过来上班!");
        }else if("冰雹".equals(weather)){
            System.out.println(name+"戴着头盔过来上班!");
        }else if("下雪".equals(weather)){
            System.out.println(name+"戴着被子过来上班!");
        }
    }
}

用户有了,再来看看通知者的接口:

/**
 * 通知者接口,subject。持有观察者接口的引用,用来通知相应的观察者
 */
public interface IWeatherStation {

    void attach(IWeatherObserver observer);

    void detach(IWeatherObserver observer);

    void notifyWeather();
}
public class WeatherStation implements IWeatherStation {

    private String[] weathers;

    //当前天气
    private String weather;

    //该集合中存储的都是需要收听天气预报的人
    private List<IWeatherObserver> observerList;

    public WeatherStation() {
        weathers = new String[]{"晴天", "雾霾", "刮风", "冰雹", "下雪"};
        observerList = new ArrayList<>();
    }

    /**
     * 观察者注册到通知者
     */
    @Override
    public void attach(IWeatherObserver observer) {
        observerList.add(observer);
    }

    @Override
    public void detach(IWeatherObserver observer) {
        observerList.remove(observer);
    }

    /**
     * 通知观察者天气发生了变化。
     */
    @Override
    public void notifyWeather() {
        for (IWeatherObserver observer : observerList
                ) {
            observer.upDate(weather);
        }
    }

    //开始工作
    public void startWork() {
        new Thread(() -> {
            while (true) {

                updateWeather();
                notifyWeather();

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    //更新天气的 方法
    public void updateWeather() {
        Random random = new Random();
        int index = random.nextInt(weathers.length);
        weather = weathers[index];
        System.out.println("当前的天气是: " + weather);
    }

}

我们需要将用户(观察者)全部注册到通知者(天气预报App)中,以便天气发生改变时通知者对每个用户作出通知。而用户再收到消息后,根据自定义的具体行为作出反应。这就是观察者模式。

运行:

    public static void main(String[] args) {
        //工人
        Emp e1 = new Emp("工人张三");
        Emp e2 = new Emp("工人李四");
        //学生
        Student s1 = new Student("娇妹");
        Student s2 = new Student("骚猪");

        WeatherStation station = new WeatherStation();
        station.attach(e1);
        station.attach(e2);
        station.attach(s1);
        station.attach(s2);

        station.startWork();

//        station.detach(s2);

//        当前的天气是: 雾霾
//        工人张三戴着消毒面具去上班!
//        工人李四戴着消毒面具去上班!
//        娇妹多吸两口去上学!
//        骚猪多吸两口去上学!
    }

源码地址

本文地址:http://blog.youkuaiyun.com/ProdigalWang/article/details/76117943

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值