java设计模式之观察者模式

来源:互联网 发布:淘宝网电脑版卖家中心 编辑:程序博客网 时间:2024/06/15 23:30

观察者设计模式:

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


下面我们可以通过天气的播报来实现观察者模式

编写一个气象站、一个工人、一个学生三个类,当气象站更新天气 的时候,要通知人做出相应的处理。

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


编写一个气象站类

/** * 气象台播报天气 * @author evan_qb * */public class WeatherStation {String[] weathers = { "晴天", "雾霾", "刮风", "冰雹", "下雪" };// 当前天气String weather;// 定义一个Weather接口,当谁需要知道天气的时候就实现这个接口// 创建一个集合用于存储需要收听的人ArrayList<Weather> list = new ArrayList<>();public void addListener(Weather e) {list.add(e);}//气象台一直工作(报天气)public void startWork(){final Random random = new Random();new Thread(){@Overridepublic void run() {while(true){//每隔3-3.5秒更新一次数据updateWeather();for (Weather e : list) {e.notifyWeather(weather);}//定义随机数  3000~3500int time = random.nextInt(501) + 3000;try {Thread.sleep(time);} catch (InterruptedException e1) {e1.printStackTrace();}}}}.start();}// 定义更新天气的方法public void updateWeather() {Random random = new Random();int index = random.nextInt(4);// 随机获取天气weather = weathers[index];System.out.println("-----------当前的天气是" + weather + "-----------");}}


定义一个接口,谁实现这个接口就给谁播报天气

/** * 通知天气的接口 * @author evan_qb * */public interface Weather {//通知所有实现这个接口的人天气状况public void notifyWeather(String weather);}

然后建立工人类和学生类实现Weather接口

工人类

/** * 工人 * 实现Weather接口 * @author evan_qb * */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+"戴着被子过来上班!");}}}

学生类

/** * 学生 * @author evan_qb */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+"等下完再去上学!");}}}

这样就实现了对特定对象播报天气

下面我们就来测试一波

public class WeatherMain {public static void main(String[] args) {//工人Emp emp = new Emp("小白");//学生Student student = new Student("evan_qb");WeatherStation station = new WeatherStation();station.addListener(emp);station.addListener(student);station.startWork();}}

运行结果如下:





原创粉丝点击