美文网首页
设计模式--- 观察者模式

设计模式--- 观察者模式

作者: 夜空最亮的9星 | 来源:发表于2018-09-07 12:07 被阅读18次

原文链接

观察者模式(Observer Pattern)

  • 别名: 依赖,发布/订阅(Another Name: Dependents, Publish/Subscribe)

  • 定义对象间的一种一对多的依赖关系,当一个对象状态发生改变时,所有依赖它的对象都得到通知并被自动更新。

  • 何时使用

    • 当一个对象的数据更新时,需要通知其他对象,而又不希望和被通知的对象形成紧耦合时
  • 优点 ...

  • 比如我们有个天气服务(主题),然后有多个使用它的客户端(观察者),包括android和iphone端app的服务(观察者),那么就可以使用这么模式。

我们需要一种结构存放天气信息(注意,省略了get、set方法!)

    //天气的消息实体
    public class WeatherInfo {
        private long time;
        private String weather;
        public WeatherInfo(long time,String weather){
            this.time = time;
            this.weather = weather;
        }
        @Override
        public boolean equals(Object obj) {
            WeatherInfo info = (WeatherInfo) obj;
            return info.time==this.time&&info.weather.equals(this.weather);
        }
    }

然后我们定义天气服务的接口(主题),以表示它应实现哪些功能:

    //主题
    public interface IWeatherService {
        void addClient(Client client);      //添加观察者
        boolean deleteClient(Client client);//删除观察者
        void notifyClients();               //通知
        void updateWeather(WeatherInfo info);//主题内容更新
    }

接着就是客户端的接口描述:

    //观察者
    public interface Client {
        void getWeather(WeatherInfo info);
    }

然后实现具体的天气服务,这里同样用到了单例模式:

    //具体主题
    public enum WeatherService implements IWeatherService{
        instance;
        private LinkedList<WeatherInfo> weatherInfos = new LinkedList<WeatherInfo>();
        private LinkedHashSet<Client> clients = new LinkedHashSet<Client>();    //存放观察者
        //添加观察者
        @Override
        public void addClient(Client client) {
            clients.add(client);
        }
        //删除观察者
        @Override
        public boolean deleteClient(Client client) {
            return clients.remove(client);
        }
        //通知观察者
        @Override
        public void notifyClients() {
            Iterator<Client> iterator = clients.iterator();
            while(iterator.hasNext()){
                iterator.next().getWeather(weatherInfos.peekFirst());
            }
        }
        //更新天气
        @Override
        public void updateWeather(WeatherInfo info) {
            if(weatherInfos.size()>0)
                if(weatherInfos.peekFirst().equals(info)) return;
            weatherInfos.push(info);
            if(clients.size()==0) return;
            notifyClients();
        }
    }

最后就是具体的客户端(观察者,此处给出两个)

    public class ClientAndroidServer implements Client {
        private static String name = "安卓服务";
        private WeatherInfo info;
        @Override
        public void getWeather(WeatherInfo info) {
            this.info = info;
            dealMsg();
        }
        private void dealMsg(){
            System.out.println(name + "收到最新天气:time="+info.getTime()+"msg="+info.getWeather()+"。马上开始推送消息...");
        }
    }
    public class ClientIphoneServer implements Client {
        private static String name = "苹果服务";
        private WeatherInfo info;
        @Override
        public void getWeather(WeatherInfo info) {
            this.info = info;
            dealMsg();
        }
        private void dealMsg(){
            System.out.println(name + "收到最新天气:time="+info.getTime()+"msg="+info.getWeather()+"。马上开始推送消息...");
        }
    }

好,现在就可以直接使用了:

    public class TestUse {
       public static void main(String args[]){
           //创建主题
           WeatherService service = WeatherService.instance;
           //添加观察者
           service.addClient(new ClientAndroidServer());
           service.addClient(new ClientIphoneServer());
           //更新主题
           service.updateWeather(new WeatherInfo(System.currentTimeMillis(), "多云"));
           service.updateWeather(new WeatherInfo(System.currentTimeMillis()+1000*60*60*24, "多云转晴"));
           service.updateWeather(new WeatherInfo(System.currentTimeMillis()+1000*60*60*24*2, "晴"));
       }
   }

运行后,控制台有如下输出

    安卓服务收到最新天气:time=1461246047007msg=多云。马上开始推送消息...
    苹果服务收到最新天气:time=1461246047007msg=多云。马上开始推送消息...
    安卓服务收到最新天气:time=1461332447007msg=多云转晴。马上开始推送消息...
    苹果服务收到最新天气:time=1461332447007msg=多云转晴。马上开始推送消息...
    安卓服务收到最新天气:time=1461418847007msg=晴。马上开始推送消息...
    苹果服务收到最新天气:time=1461418847007msg=晴。马上开始推送消息...

相关文章

  • 观察者设计模式

    每周学点Java设计模式__观察者设计模式 本次继续更新java23中设计模式之一——观察者模式。 观察者模式(有...

  • RxJava基础—观察者模式

    设计模式-观察者模式 观察者模式:观察者模式(有时又被称为发布(publish )-订阅(Subscribe)模式...

  • 设计模式02-观察者者设计模式

    [toc] 设计模式02-观察者者设计模式 主要来源Head First设计模式(书)观察者设计模式是JDK中使用...

  • 11.9设计模式-观察者模式-详解

    设计模式-观察者模式 观察者模式详解 观察者模式在android中的实际运用 1.观察者模式详解 2.观察者模式在...

  • RxJava设计模式与原理

    标准观察者设计模式 RxJava是一种特殊的观察者模式,首先我们先来看标准的观察者设计模式。在标准观察者模式中,存...

  • 设计模式

    常用的设计模式有,单例设计模式、观察者设计模式、工厂设计模式、装饰设计模式、代理设计模式,模板设计模式等等。 单例...

  • Guava源码分析——EventBus

    EventBus的设计理念是基于观察者模式的,可以参考设计模式(1)—观察者模式先来了解该设计模式。 1、程序示例...

  • 设计模式之观察者模式

    设计模式之观察者模式 本篇是设计模式系列博客的第四篇,本篇主要学习设计模式中的第二个行为型模式---观察者模式。 ...

  • PHP设计模式之观察者模式

    PHP设计模式之观察者模式

  • Android中涉及的模式

    我的Java设计模式-建造者模式 我的Java设计模式-观察者模式 重学设计模式之单例模式

网友评论

      本文标题:设计模式--- 观察者模式

      本文链接:https://www.haomeiwen.com/subject/xjfcgftx.html