您的位置:首页 > 其它

设计模式之观察者模式之一、引出观察者mosh

2016-06-19 22:54 288 查看
一、气象站提供的类

package org.observer.pt;

/**
*
* @author mexican 项目描述:该类有气象站提供气象的温度、气压、湿度,当数据有变化的时候,直接公布到消息版块,而这个举动是实时更改的
*/
public class WeatherData {
// 温度
private int wd;
// 气压
private int qy;
// 湿度
private int sd;
// 信息公布
private CurrentConditions cc;

// 构造气象类的时候,将公告栏给初始化
public WeatherData(CurrentConditions cc) {
this.cc = cc;
}

public void dataChange() {
// 当气象局获取的气象数据发生改变会调用dataChange这个method,然后直接公布到信息栏
cc.update(getWd(), getQy(), getSd());
}

// 该方法用于模拟气象站获取到数据的时候,将气象数据设置进去
public void setData(int wd, int qy, int sd) {
this.wd = wd;
this.qy = qy;
this.sd = sd;
//这里表名气象站有新的数据了,就直接调用dataChange
dataChange();
}

public int getWd() {
return wd;
}

public void setWd(int wd) {
this.wd = wd;
}

public int getQy() {
return qy;
}

public void setQy(int qy) {
this.qy = qy;
}

public int getSd() {
return sd;
}

public void setSd(int sd) {
this.sd = sd;
}

}
二、第三方对接公司气象公告板
package org.observer.pt;

/**
*
* @author mexican 公告板
*/
public class CurrentConditions {
/**
* update 方法用于更新数据
*/
//温度
private int wd;
//气压
private int qy;
//湿度
private int sd;
/**
*
* @param wd 温度
* @param qy 气压
* @param sd 湿度
* desc:用于接受气象站也就是WeatherData提供的气象数据
*/
public void update(int wd,int qy,int sd) {
this.wd=wd;
this.qy=qy;
this.sd=sd;
//当发生改变之后立即现实公布气象结果
display();
}

/**
* 用于现实当前气象数据结果
*/
public void display() {
//这里简单模拟就直接打印出来
System.out.println("****今日温度是:"+wd+"****");
System.out.println("****今日气压是:"+qy+"****");
System.out.println("****今日湿度是:"+sd+"****");
}
}


三、测试结果
package org.observer.pt;

/**
*
* @author mexican 公告板
*/
public class CurrentConditions {
/**
* update 方法用于更新数据
*/
//温度
private int wd;
//气压
private int qy;
//湿度
private int sd;
/**
*
* @param wd 温度
* @param qy 气压
* @param sd 湿度
* desc:用于接受气象站也就是WeatherData提供的气象数据
*/
public void update(int wd,int qy,int sd) {
this.wd=wd;
this.qy=qy;
this.sd=sd;
//当发生改变之后立即现实公布气象结果
display();
}

/**
* 用于现实当前气象数据结果
*/
public void display() {
//这里简单模拟就直接打印出来
System.out.println("****今日温度是:"+wd+"****");
System.out.println("****今日气压是:"+qy+"****");
System.out.println("****今日湿度是:"+sd+"****");
}
}

****今日温度是:23****
****今日气压是:50****
****今日湿度是:100****


总结:首先第三方公司CurrentConditions公布今日气象数据这种方式能实现,如果再有例外一个公司需要接入气象站,用于计算明日的气象数据,温度、气压,湿度。那么有的单独写一个明日的气象公告栏,从而在气象站中的dataChange方法,有的添加明日公告栏的消息的方法,进而有的重新进行编译气象站这个类,气象站应该作为单独的线程进行运行,从而引出观测站模式。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: