首页 > 其他 > 详细

设计模式之观察者模式

时间:2015-12-26 15:05:11      阅读:238      评论:0      收藏:0      [点我收藏+]

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

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

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

  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();
    }
    
}

 

设计模式之观察者模式

原文:http://www.cnblogs.com/lyjs/p/5078050.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!