设计模式之观察者模式

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

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

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

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

 

posted @ 2015-12-26 14:21  好人难寻  阅读(160)  评论(0编辑  收藏  举报