zoukankan      html  css  js  c++  java
  • 设计模式之观察者模式

    一、观察者设计模式能够解决什么问题呢?

    当一个对象发生指定的动作时,要通过另外一个对象做出相应的处理。

    二、观察者设计模式的步骤:

    1. 当前对象发生指定动作的时候,要通知另外一个对象做出相应的处理,这时候应该把对方的相应处理方法定义在接口上。
    2. 在当前对象维护接口的引用,当前对象发生指定的动作这时候即可调用接口中的方法了。

    三、经典的天气预报

    1. 编写一个气象站类,发布天气。 
    2. 编写一个接口,定义的是根据天气做出安排的方法。
    3. 编写一个学生类,根据天气安排自己的出行。

    WeatherStation 类:

    public class WeatherStation {
        
        String [] weathers={"晴天","雾霭","下雨天"};
        //当前天气
        String weather;
        //该集合中存储的是需要收听天气
        ArrayList<Weather> list=new ArrayList<Weather>();
        
        public void addListener(Weather e){
            list.add(e);
        }
        
        //开始工作
        public void startWork() throws Exception{
            Random random=new Random();
            while(true){
                updateWeather();
                for(Weather e:list){  //通知调用者
                    e.notifyWeather(weather);
                }
                int s=random.nextInt(501)+1000;
                Thread.sleep(s);
            }
        }
        
        
        
        public void updateWeather(){  //更新天气
            Random random=new Random();
            int index=random.nextInt(3);
            weather=weathers[index];
            System.out.println("当前天气为:"+weather);
        }
    }
    Weather 接口:
    package observer;
    
    public interface Weather {
        //订阅天气预报
        public void notifyWeather(String weather);
    }

    Student 类:

    package observer;
    
    public class Student implements Weather{
        
        String name;
        
        public Student(String name) {
            this.name = name;
        }
    
        @Override
        public void notifyWeather(String weather) {
            if("雾霭".equals(weather)){
                System.out.println("今天天气是"+weather+"  "+name+"带着口罩去上学");
            }else if("晴天".equals(weather)){
                System.out.println("今天天气是"+weather+"  "+name+"开开心心去上学");
            }else{
                System.out.println("今天天气是"+weather+"  "+name+"在家休息");
            }
            
        }
    
    }

    测试类:

    public class WeatherMain {
        public static void main(String[] args) throws Exception {
            Student student=new Student("小明");
            Student student1=new Student("老王");
            WeatherStation weatherStation=new WeatherStation();
            weatherStation.addListener(student);
            weatherStation.addListener(student1);
            weatherStation.startWork();
        }
        
    }

     

  • 相关阅读:
    MySql 获取当前节点及递归所有上级节点
    MySql创建树结构递归查询存储过程
    F2工作流引擎Web层全新扁平化UI上线
    F2工作流引擎参与者类型成员的交、并、互拆计算规则
    F2工作流引擎之组织用户模型(四)
    F2工作流引擎之 工作流运转模型(三)
    F2工作流引擎之 概述(一)
    离线安装docker,并导入docker镜像
    sudo: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set 的解决办法
    yml 文件中使用环境变量
  • 原文地址:https://www.cnblogs.com/lyjs/p/5078050.html
Copyright © 2011-2022 走看看