java设计模式之内容观察者
观察者模式定义了对象之间一对多的关系,可观察者用一个共同的接口来更新观察者,观察者与可观察者用松耦合方式结合,可观察着不知道观察者的细节,只知道观察者实现了观察者的接口。OO原则:1封装变化--找出程序中会变化的方面,然后将其和固定不变的方面相分离。
2针对接口编程,不针对实现编程。
3多用组合,少用继承。
4为交互对象之间的松耦合设计而努力。
代码贴:
首先,定义一个可观察者的接口:Subject.java
package com.godinsec.liu.in;
public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
}
然后定义观察者的接口:Observer.java
package com.godinsec.liu.in;
public interface Observer {
public void update(float temp, float humidity, float pressure);
}然后定义显示数据的接口:
package com.godinsec.liu.in;
public interface DisplayElement {
public void display();
}下面通过实现可观察者与观察者的接口来通知观察者:
package com.godinsec.liu.data;
import java.util.ArrayList;
import com.godinsec.liu.in.Observer;
import com.godinsec.liu.in.Subject;
public class WeatherData implements Subject{
private ArrayList observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherData(){
observers = new ArrayList();
}
@Override
public void registerObserver(Observer o) {
// TODO Auto-generated method stub
observers.add(o);
}
@Override
public void removeObserver(Observer o) {
// TODO Auto-generated method stub
int i = observers.indexOf(o);
if(i >= 0){
observers.remove(i);
}
}
@Override
public void notifyObservers() {
// TODO Auto-generated method stub
for(int i=0; i < observers.size(); i++){
Observer observer = (Observer) observers.get(i);
observer.update(temperature, humidity, temperature);
}
}
public void measurementschanged(){
notifyObservers();
}
public void setMeasurements(float temperature,float humidity,float pressure){
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
measurementschanged();
}
}
package com.godinsec.liu.data;
import com.godinsec.liu.in.DisplayElement;
import com.godinsec.liu.in.Observer;
import com.godinsec.liu.in.Subject;
public class CurrentConditionsDisplay implements Observer, DisplayElement{
private float temperature;
private float humidity;
private Subject weatherData;
public CurrentConditionsDisplay(Subject weatherData){
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
@Override
public void update(float temp, float humidity, float pressure) {
// TODO Auto-generated method stub
this.temperature = temp;
this.humidity = humidity;
display();
}
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("Current conditions:" + temperature
+ "F degrees and " + humidity + "% humidity");
}
}
这样的话,可观察者与观察者的类写完了,然后就是测试类了:
package com.godinsec.liu.data;
public class WeatherStation {
public static void main(String args[]){
WeatherData weatherData = new WeatherData();
CurrentConditionsDisplay currentConditionsDisplay =
new CurrentConditionsDisplay(weatherData);
weatherData.setMeasurements(80, 65, 30.4f);
weatherData.setMeasurements(80.2f, 45, 34.7f);
weatherData.setMeasurements(90, 23, 67.6f);
}
}
大神锕。
页:
[1]