标签:rri sig oat pattern vat tco oid add des
package DesignPattern;
import java.util.ArrayList;
public class ObserverPattern {
//来自Head First 设计模式
interface Subject{
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
interface Observer{
void update(float temperature,float humidity,float pressure);
}
interface DisplayElement{
void display();
}
public static class WeathData implements Subject{
private ArrayList<Observer> observers;
private float temperature;
private float humidity;
private float pressure;
public WeathData(){
observers= new ArrayList<>();
}
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
int i=observers.size();
if(i>=0) {
observers.remove(observer);
}
}
@Override
public void notifyObservers() {
for(Observer observer:observers){
observer.update(temperature,humidity,pressure);
}
}
public void measurementChanged(){
notifyObservers();
}
public void setMeasurements(float t,float h,float p){
this.temperature=t;
this.humidity=h;
this.pressure=p;
measurementChanged();
}
}
public static class CurrentConditionsDisplay implements Observer,DisplayElement{
private float temperature;
private float humidity;
private Subject weatherData;
CurrentConditionsDisplay(Subject weatherData){
this.weatherData=weatherData;
weatherData.registerObserver(this);
}
@Override
public void update(float t,float h,float p) {
this.temperature=t;
this.humidity=h;
display();
}
@Override
public void display() {
System.out.println("Current conditions:"+temperature+"F degrees and "+humidity+"% humidity.");
}
}
public static class StaticsDisplay implements Observer,DisplayElement{
private float temperature;
private Subject weatherData;
StaticsDisplay(Subject weatherData){
this.weatherData=weatherData;
weatherData.registerObserver(this);
}
@Override
public void update(float temperature, float humidity, float pressure) {
this.temperature=temperature;
display();
}
@Override
public void display() {
System.out.println("Statics temperature:"+temperature);
}
}
public static void main(String[] args) {
WeathData weathData = new WeathData();
CurrentConditionsDisplay ccd = new CurrentConditionsDisplay(weathData);
StaticsDisplay sd = new StaticsDisplay(weathData);
weathData.setMeasurements(80,65,30.4f);
weathData.setMeasurements(82,70,29.2f);
weathData.setMeasurements(78,90,29.2f);
}
}
标签:rri sig oat pattern vat tco oid add des
原文地址:https://www.cnblogs.com/zhouyu0-0/p/10724329.html