观察者设计模式

来源:互联网 发布:知乎 日本人写的书 编辑:程序博客网 时间:2024/06/05 05:31

 观察者设计模式:观察者设计模式解决的问题是当一个对象发生指定的动作时,要通过另外一个对象做出相应的处理。

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


 需求: 编写一个气象站、一个工人两个类,当气象站更新天气 的时候,要通知人做出相应的处理。 
问题1: 气象站更新了多次天气,然后人才做一次的处理。

应该由气象站通知人,而不是人去关注天气:就在更新天气的updateWeather();后面,人就做出反应e.notifyWeather(weather);


问题2: 目前气象站只能通知一个人而已。

用集合来存储所有的人,遍历集合使每个人获得天气从而做出相应的处理


问题3: 在现实生活中出了工人群体要关注天气,其他 的群体也需要关注天气

使用接口,哪个群体想要收到天气预报的通知,都要实现该接口

Weather.java:

//订阅天气预报的接口public interface Weather {public void notifyWeather(String weather);}

WeatherStation.java:

//气象站public class WeatherStation {String[] weathers = {"晴天","雾霾","刮风","冰雹","下雪"};//当前天气String  weather ;//该集合中存储的都是需要收听天气预报的人ArrayList<Weather> list = new ArrayList<Weather>();  //程序设计讲究低耦合---->尽量不要让一个类过分依赖于另外一个类。public void addListener(Weather e){list.add(e);}//开始工作public void startWork() {final Random random = new Random();new Thread(){@Overridepublic void run() {while(true){ updateWeather(); // 每1~1.5秒更新一次天气  1000~1500for(Weather e : list){e.notifyWeather(weather);}int  s = random.nextInt(501)+1000; //  500try {Thread.sleep(s);} 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);}}

Emp.java:

//人 是要根据天气做出相应的处理的。public class Emp implements Weather{String name;public Emp(String name) {this.name = name;}//人是要根据天气做出相应的处理的。  "晴天","雾霾","刮风","冰雹","下雪"public void notifyWeather(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+"戴着被子过来上班!");}}}

Student.java:

public class Student implements Weather{String name;public Student(String name) {super();this.name = name;}public void notifyWeather(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+"等下完再去上学!");}}}

WeatherMain.java:

import java.util.Random;public class WeatherMain {public static void main(String[] args) throws Exception {//工人Emp e = new Emp("小明");Emp e2 = new Emp("如花");//学生Student s1 = new Student("狗娃");Student s2 = new Student("狗剩");WeatherStation station = new WeatherStation();station.addListener(e);station.addListener(e2);station.addListener(s1);station.addListener(s2);station.startWork();}}







0 0