以天气预报项目引入观察者模式
- 气象站可以将每天测量到的温度,湿度,气压等等以公告的形式发布给第三方。
需要设计开放型 API,便于其他第三方也能接入气象站获取数据
,提供温度、气压、湿度等接口- 测量数据更新时,要能实时的通知给第三方
1.传统方案
1.1.类图设计及编码实现:
a.类图设计:
b.编码实现:
- 1.第三方网站1
public class Website1 {
//温度
private float temperature;
//湿度
private float humidity;
//气压
private float pressure;
//修改气象数据
public void update(float temperature, float humidity, float pressure){
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
display();
}
//显示气象数据
public void display(){
System.out.println("----网站1气象数据服务----");
System.out.println("温度:" + temperature);
System.out.println("湿度:" + humidity);
System.out.println("气压:" + pressure);
}
}
- 2.第三方网站2:
public class Website2 {
//温度
public float temperature;
//湿度
public float humidity;
//气压
public float pressure;
//修改气象数据
public void update(float temperature, float humidity, float pressure){
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
display();
}
//显示气象数据
public void display(){
System.out.println("----网站2气象数据服务----");
System.out.println("温度:" + temperature);
System.out.println("湿度:" + humidity);
System.out.println("气压:" + pressure);
}
}
- 3.
气象数据类
,包含最新的天气情况信息,当数据有更新时,就主动的调用setData方法,这样第三方网站就能看到最新消息
public class WeatherData {
//温度;
private float temperature;
//湿度;
private float humidity;
//气压;
private float pressure;
// 聚合第三方网站,方便通知最小消息
private Website1 website1;
private Website2 website2;
public void setWebsite1(Website1 website1) {
this.website1 = website1;
}
public void setWebsite2(Website2 website2) {
this.website2 = website2;
}
//修改气象数据
public void setData(float temperature, float humidity, float pressure){
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
website1.update(temperature,humidity,pressure);
website2.update(temperature,humidity,pressure);
}
}
- 4.测试:
public class Clint {
public static void main(String[] args) {
WeatherData weatherData = new WeatherData();
Website1 website1 = new Website1();
Website2 website2 = new Website2();
weatherData.setWebsite1(website1);
weatherData.setWebsite2(website2);
//设置气象数据
weatherData.setData(50.0f,50.0f,50.0f);
//修改气象数据
System.out.println("----气象台修改气象数据----");
weatherData.setData(10.0f,10.0f,10.0f);
}
}
- 5.结果:
----网站1气象数据服务----
温度:50.0
湿度:50.0
气压:50.0
----网站2气象数据服务----
温度:50.0
湿度:50.0
气压:50.0
----气象台修改气象数据----
----网站1气象数据服务----
温度:10.0
湿度:10.0
气压:10.0
----网站2气象数据服务----
温度:10.0
湿度:10.0
气压:10.0
c.问题分析:
- 1.无法在运行时动态的添加第三方。
- 2.当增加一个第三方,需要修改气象数据类的方法,不利于维护
2.观察者模式
2.1.基本介绍:
a.定义:
- 1.又被称为
发布-订阅(Publish/Subscribe)模式
,它定义了一种对象之间一对多的依赖关系
,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态变化时,会通知所有的观察者对象,使他们能够自动更新自己
b.在观察者模式中有如下角色:
- 1.
Subject
:抽象主题(抽象被观察者),抽象主题角色把所有观察者对象保存在一个集合里,每个主题都可以有任意数量的观察者,抽象主题提供一个接口,可以增加和删除观察者对象。 - 2.
ConcreteSubject
:具体主题(具体被观察者),该角色将有关状态存入具体观察者对象,在具体主题的内部状态发生改变时,给所有注册过的观察者发送通知。 - 3
.Observer
:抽象观察者,是观察者的抽象类,它定义了一个更新接口,使得在得到主题更改通知时更新自己。 - 4.
ConcrereObserver
:具体观察者,实现抽象观察者定义的更新接口,以便在得到主题更改通知时更新自身的状态。
c.类图设计:
- 1.观察者模式中
被依赖
的对象为Subject
,依赖的对象
为Observer
,Subject 通知 Observer 变化,比如这里的气象数据是 Subject, 网站是Observer。- Subject:登记注册、移除和通知
- Observer:接收输入
2.2.代码实现
- 1.观察者接口:管理不同的用户
// 观察者接口 --> 管理不同的用户
public interface Observer {
//更新天气数据;(温度,气压,湿度)
public void update(float temperature, float humidity,float pressure);
}
- 2.两个第三方网站
public class Website1 implements Observer{
//温度;
private float temperature;
//湿度;
private float humidity;
//气压;
private float pressure;
//更新气象数据;
public void update(float temperature,float humidity,float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
display();
}
//显示气象数据
public void display(){
System.out.println("----网站1气象数据服务----");
System.out.println("温度:" + temperature);
System.out.println("湿度:" + humidity);
System.out.println("气压:" + pressure);
}
}
public class Website2 implements Observer{
//温度;
private float temperature;
//湿度;
private float humidity;
//气压;
private float pressure;
//更新气象数据;
public void update(float temperature,float humidity,float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
display();
}
//显示气象数据
public void display(){
System.out.println("----网站2气象数据服务----");
System.out.println("温度:" + temperature);
System.out.println("湿度:" + humidity);
System.out.println("气压:" + pressure);
}
}
- 3.定义平台的管理接口
public interface Subject {
//注册,增加;
public void registerObserver(Observer observer);
//移出;
public void remove(Observer observer);
//通知所有的注册的用户
public void notifyObserver();
}
- 4.气象数据类
public class WeatherData implements Subject{
//温度;
private float temperatrue;
//湿度;
private float humidity;
//气压;
private float pressure;
//观察者(用户集合)
private ArrayList<Observer> observerArrayList;
//初始化信息;
public WeatherData() {
observerArrayList = new ArrayList<Observer>();
}
//设置传入数据;
public void setData(float temperature, float humidity, float pressure) {
this.temperatrue = temperature;
this.humidity = humidity;
this.pressure = pressure;
notifyObserver();
}
public void registerObserver(Observer observer) {
observerArrayList.add(observer);
}
public void remove(Observer observer) {
//若存在就移除;
if(observerArrayList.contains(observer)){
observerArrayList.remove(observer);
}
}
public void notifyObserver() {
for (int i = 0; i < observerArrayList.size(); i++) {
observerArrayList.get(i).update(this.humidity, this.temperatrue, this.pressure);
}
}
}
- 5.客户端测试:
public class CLient {
public static void main(String[] args) {
WeatherData weatherData = new WeatherData();
Website1 website1 = new Website1();
Website2 website2 = new Website2();
//添加发布的平台;
weatherData.registerObserver(website1);
weatherData.registerObserver(website2);
//设置气象数据;
weatherData.setData(31f,60f,180f);
//修改气象数据
weatherData.setData(20f,40f,60f);
}
}
- 6.结果测试:
----网站1气象数据服务----
温度:31.0
湿度:60.0
气压:180.0
----网站2气象数据服务----
温度:31.0
湿度:60.0
气压:180.0
----网站1气象数据服务----
温度:20.0
湿度:40.0
气压:60.0
----网站2气象数据服务----
温度:20.0
湿度:40.0
气压:60.0
3.案例2来理解观察者模式:
a.案例:微信公众号
- 1.在使用微信公众号时,大家都会有这样的体验,当你关注的公众号中有新内容更新的话,它就会推送给关注公众号的微信用户端。我们使用观察者模式来模拟这样的场景,微信用户就是观察者,微信公众号是被观察者,有多个的微信用户关注了程序猿这个公众号
b.类图如下:
c.代码如下:
- 1.定义抽象观察者类,里面定义一个更新的方法
public interface Observer {
void update(String message);
}
- 2.定义具体观察者类,微信用户是观察者,里面实现了更新的方法
public class WeixinUser implements Observer {
// 微信用户名
private String name;
public WeixinUser(String name) {
this.name = name;
}
@Override
public void update(String message) {
System.out.println(name + "-" + message);
}
}
- 3.定义抽象主题类,提供了attach、detach、notify三个方法
public interface Subject {
//增加订阅者
public void attach(Observer observer);
//删除订阅者
public void detach(Observer observer);
//通知订阅者更新消息
public void notify(String message);
}
- 4.微信公众号是具体主题(具体被观察者),里面存储了订阅该公众号的微信用户,并实现了抽象主题中的方法
public class SubscriptionSubject implements Subject {
//储存订阅公众号的微信用户
private List<Observer> weixinUserlist = new ArrayList<Observer>();
@Override
public void attach(Observer observer) {
weixinUserlist.add(observer);
}
@Override
public void detach(Observer observer) {
weixinUserlist.remove(observer);
}
@Override
public void notify(String message) {
for (Observer observer : weixinUserlist) {
observer.update(message);
}
}
}
- 5.客户端程序:
public class Client {
public static void main(String[] args) {
SubscriptionSubject mSubscriptionSubject=new SubscriptionSubject();
//创建微信用户
WeixinUser user1=new WeixinUser("孙悟空");
WeixinUser user2=new WeixinUser("猪悟能");
WeixinUser user3=new WeixinUser("沙悟净");
//订阅公众号
mSubscriptionSubject.attach(user1);
mSubscriptionSubject.attach(user2);
mSubscriptionSubject.attach(user3);
//公众号更新发出消息给订阅的微信用户
mSubscriptionSubject.notify("传智黑马的专栏更新了");
}
}
4.观察者模式优缺点与使用场景:
4.1.优点:
- 降低了目标与观察者之间的耦合关系,两者之间是抽象耦合关系。
- 被观察者发送通知,所有注册的观察者都会收到信息【可以实现广播机制】,这样,我们增加观察者(这里可以理解成一个新的公告板),就不需要去修改核心类WeatherData,遵守了 ocp 原则
4.2.缺点
- 如果观察者非常多的话,那么所有的观察者收到被观察者发送的通知会耗时
- 如果被观察者有循环依赖的话,那么被观察者发送通知会使观察者循环调用,会导致系统崩溃
4.3.使用场景
- 1.对象间存在一对多关系,一个对象的状态发生改变会影响其他对象
- 2.当一个抽象模型有两个方面,其中一个方面依赖于另一方面时
5.观察者模式在 Jdk 应用的源码分析:
在 Java 中,通过 java.util.Observable 类和 java.util.Observer 接口定义了观察者模式,只要实现它们的子类就可以编写观察者模式实例。
5.1.Jdk 的 Observable 类就使用了观察者模式
public class Observable {
private boolean changed = false;
private Vector<Observer> obs;
public Observable() {
obs = new Vector<>();
}
public synchronized void addObserver(Observer o) {
if (o == null)
throw new NullPointerException();
if (!obs.contains(o)) {
obs.addElement(o);
}
}
public synchronized void deleteObserver(Observer o) {
obs.removeElement(o);
}
public void notifyObservers() {
notifyObservers(null);
}
public void notifyObservers(Object arg) {
Object[] arrLocal;
synchronized (this) {
if (!changed)
return;
arrLocal = obs.toArray();
clearChanged();
}
for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
}
public synchronized void deleteObservers() {
obs.removeAllElements();
}
protected synchronized void setChanged() {
changed = true;
}
protected synchronized void clearChanged() {
changed = false;
}
public synchronized boolean hasChanged() {
return changed;
}
public synchronized int countObservers() {
return obs.size();
}
}
public interface Observer {
void update(Observable o, Object arg);
}
- Observable的作用等价于前面的Subject
- Observable 是类,不是接口,类中已经实现了核心的方法,即管理 Observer 的方法
- Observer 的作用等价于前面的Observer,有 update方法
- Observable 和 Observer 的使用方法和前面讲过的一样,只是 Observable 是类,通过继承来实现观察者模式。