[color=blue][size=medium]观察者模式---在对象之间以多对一的依赖,这样一来,当一个对象改变状态,依赖它的对象都会收到通知,并自动更新.[/size][/color]
[color=blue]书中以报社和订报者来形容,真是恰到好处(也有注册,删除,通知等功能)![/color]
[color=red]首先是主题接口(也即被观察者接口),其中定义了注册,删除,通知观察者等方法:[/color]
[color=red] 接着是被观察者(也即被依赖者,其实现了上面的接口):[/color]
[color=red] 跟着就是观察者接口:[/color]
[color=red]接着当然观察者(实现了上面的观察者接口):[/color]
[color=red]最后少不了一个测试类:[/color]
[color=red]其中也用到了一个显示信息的接口,对模式没什么影响,一并赋上:[/color]
[color=blue]书中以报社和订报者来形容,真是恰到好处(也有注册,删除,通知等功能)![/color]
[color=red]首先是主题接口(也即被观察者接口),其中定义了注册,删除,通知观察者等方法:[/color]
package com.jie.observer;
public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
}
[color=red] 接着是被观察者(也即被依赖者,其实现了上面的接口):[/color]
package com.jie.observer;
import java.util.*;
public class WeatherData implements Subject{
private ArrayList observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherData()
{
observers=new ArrayList();
}
public void registerObserver(Observer o)
{
observers.add(o);
}
public void removeObserver(Observer o)
{
int i=observers.indexOf(o);
if(i>=0)
{
observers.remove(i);
}
}
public void notifyObservers()
{
for(int i=0;i<observers.size();i++)
{
Observer observer=(Observer)observers.get(i);
observer.update(temperature,humidity,pressure);
}
}
public void measurementsChanged()
{
notifyObservers();
}
public void setMeasurements(float temperature,float humidity,float pressure)
{
this.temperature=temperature;
this.humidity=humidity;
this.pressure=pressure;
measurementsChanged();
}
}
[color=red] 跟着就是观察者接口:[/color]
package com.jie.observer;
public interface Observer {
public void update(float temperature,float humidity,float pressure);
}
[color=red]接着当然观察者(实现了上面的观察者接口):[/color]
package com.jie.observer;
public class CurrentConditionsDisplay implements Observer,DisplayElement{
private float temperature;
private float humidity;
private float pressure;
private Subject weatherData;
public CurrentConditionsDisplay(Subject weatherData)
{
this.weatherData=weatherData;
weatherData.registerObserver(this);
}
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("Current conditions:"+temperature+"F degrees and "+
humidity+"% humidity "+pressure+" pressure");
}
}
[color=red]最后少不了一个测试类:[/color]
package com.jie.observer;
public class Test {
public static void main(String [] args)
{
WeatherData wd=new WeatherData();
CurrentConditionsDisplay ccd=new CurrentConditionsDisplay(wd);
wd.setMeasurements(21, 13, 30.4f);
wd.setMeasurements(1, 2, 3f);
}
}
[color=red]其中也用到了一个显示信息的接口,对模式没什么影响,一并赋上:[/color]
package com.jie.observer;
public interface DisplayElement {
public void display();
}