`

观察者模式(observer)

 
阅读更多
设计模式中观察者模式的实现有很多方式,这里列出两种实现方式
1、主题实现Subject接口,观察者实现Observer、DisplayElement接口,其中,Subject、Observer、DisplayElement接口都是用户自定义的接口。
package com.interfaces;

public interface Subject {
	
	public void registerObserver(Observer o);
	
	public void removeObserver(Observer  o);
	
	public void notifyObservers();
	
}


package com.interfaces;

public interface Observer {
	
	public void update(float temp, float humidity, float pressure);

}


package com.interfaces;

public interface DisplayElement {
	
	public void display();

}


package com.theme;

import java.util.ArrayList;

import com.interfaces.Observer;
import com.interfaces.Subject;

@SuppressWarnings("unchecked")
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 notifyObservers() {
		for(int i = 0; i < observers.size();i++){
			Observer observer = (Observer)observers.get(i);
			observer.update(temperature, humidity, pressure);
		}
	}

	@Override
	public void registerObserver(Observer o) {
		observers.add(o);
	}

	@Override
	public void removeObserver(Observer o) {

		int i = observers.indexOf(o);
		if(i>=0){
			observers.remove(i);
		}
	}

	public void setMeasurements(float temperature,float humidity,float pressure){
		this.humidity = humidity;
		this.temperature = temperature;
		this.pressure = pressure;
		measurementsChanged();
	}

	public void measurementsChanged(){
		notifyObservers();
	}
}


package com.observers;

import com.interfaces.DisplayElement;
import com.interfaces.Observer;
import com.interfaces.Subject;

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);
	}

	@Override
	public void update(float temp, float humidity, float pressure) {
		this.temperature = temp;
		this.humidity = humidity;
		this.pressure = pressure;
		display();
	}

	@Override
	public void display() {
		System.out.println("Current conditions : "+temperature +"F degrees and "+humidity+"% humidity and pressure is :"+pressure);
	}
}


package com.observers;

import com.interfaces.DisplayElement;
import com.interfaces.Observer;
import com.theme.WeatherData;

public class ForecastDisplay implements DisplayElement, Observer {
	private float currentPressure = 29.92f;  
	private float lastPressure;
	private WeatherData weatherData;

	public ForecastDisplay(WeatherData weatherData) {
		this.weatherData = weatherData;
		weatherData.registerObserver(this);
	}

	public void update(float temp, float humidity, float pressure) {
		lastPressure = currentPressure;
		currentPressure = pressure;

		display();
	}

	public void display() {
		System.out.print("Forecast: ");
		if (currentPressure > lastPressure) {
			System.out.println("Improving weather on the way!");
		} else if (currentPressure == lastPressure) {
			System.out.println("More of the same");
		} else if (currentPressure < lastPressure) {
			System.out.println("Watch out for cooler, rainy weather");
		}
	}

}



package com.observers;

import com.interfaces.DisplayElement;
import com.interfaces.Observer;
import com.theme.WeatherData;

public class StatisticsDisplay implements Observer, DisplayElement {

	private float maxTemp = 0.0f;
	private float minTemp = 200;
	private float tempSum= 0.0f;
	private int numReadings;
	private WeatherData weatherData;

	public StatisticsDisplay(WeatherData weatherData) {
		this.weatherData = weatherData;
		weatherData.registerObserver(this);
	}

	public void update(float temp, float humidity, float pressure) {
		tempSum += temp;
		numReadings++;

		if (temp > maxTemp) {
			maxTemp = temp;
		}

		if (temp < minTemp) {
			minTemp = temp;
		}

		display();
	}

	public void display() {
		System.out.println("Avg/Max/Min temperature = " + (tempSum / numReadings)
				+ "/" + maxTemp + "/" + minTemp);
	}

}


package com.test;

import com.observers.CurrentConditionsDisplay;
import com.observers.ForecastDisplay;
import com.observers.StatisticsDisplay;
import com.theme.WeatherData;

public class WeatherStation {
	
	public static void main(String[] args) {
		
		WeatherData weatherData = new WeatherData();
		
		new CurrentConditionsDisplay(weatherData);
		new StatisticsDisplay(weatherData);
		new ForecastDisplay(weatherData);

		weatherData.setMeasurements(80, 65, 30.4f);
		weatherData.setMeasurements(82, 70, 29.2f);
		weatherData.setMeasurements(78, 90, 29.2f);
	}

}


测试结果为:
Current conditions : 80.0F degrees and 65.0% humidity and pressure is :30.4
Avg/Max/Min temperature = 80.0/80.0/80.0
Forecast: Improving weather on the way!
Current conditions : 82.0F degrees and 70.0% humidity and pressure is :29.2
Avg/Max/Min temperature = 81.0/82.0/80.0
Forecast: Watch out for cooler, rainy weather
Current conditions : 78.0F degrees and 90.0% humidity and pressure is :29.2
Avg/Max/Min temperature = 80.0/82.0/78.0
Forecast: More of the same


运行方式:每当主题的状态有所变化时,就会通知每一个观察者。观察者可以动态的来注册主题或者移除对主题的关注,主题根本不知道有哪些观察者。这个实现方式的优点是:主题会每一次状态的改变都会通知所有的观察者,这也会带来缺点,因为并不是主题每一次的状态改变的信息都是每个观察者所需要的,主题是将每次的改变推给观察者们的,而不是观察者们去拿的。

2、主题继承Observale类,Observable类封装了一些方法,观察者实现了Observer、DisplayElement接口

package com.interfaces;

public interface DisplayElement {
	public void display();
}


package com.theme;

import java.util.Observable;

public class WeatherData extends Observable {

	private float temperature;

	private float humidity;

	private float pressure;

	public WeatherData(){

	}

	public void measurementsChanged(){
		this.setChanged();
		this.notifyObservers();
	}

	public void setMeasurements(float temperature,float humidity,float pressure){
		this.temperature = temperature;
		this.humidity = humidity;
		this.pressure = pressure;
		measurementsChanged();
	}

	public float getTemperature() {
		return temperature;
	}

	public float getHumidity() {
		return humidity;
	}

	public float getPressure() {
		return pressure;
	}
}


package com.observers;

import java.util.Observable;
import java.util.Observer;

import com.interfaces.DisplayElement;
import com.theme.WeatherData;

public class CurrentConditionsDisplay implements Observer, DisplayElement {
	private float temperature;
	private float humidity;

	public CurrentConditionsDisplay(Observable observable) {
		observable.addObserver(this);
	}

	public void update(Observable obs, Object arg) {
		if (obs instanceof WeatherData) {
			WeatherData weatherData = (WeatherData)obs;
			this.temperature = weatherData.getTemperature();
			this.humidity = weatherData.getHumidity();
			display();
		}
	}

	public void display() {
		System.out.println("Current conditions: " + temperature 
				+ "F degrees and " + humidity + "% humidity");
	}
}


package com.observers;

import java.util.Observable;
import java.util.Observer;

import com.interfaces.DisplayElement;
import com.theme.WeatherData;

public class ForecastDisplay implements Observer, DisplayElement {
	private float currentPressure = 29.92f;  
	private float lastPressure;

	public ForecastDisplay(Observable observable) {
		observable.addObserver(this);
	}

	public void update(Observable observable, Object arg) {
		if (observable instanceof WeatherData) {
			WeatherData weatherData = (WeatherData)observable;
			lastPressure = currentPressure;
			currentPressure = weatherData.getPressure();
			display();
		}
	}

	public void display() {
		System.out.print("Forecast: ");
		if (currentPressure > lastPressure) {
			System.out.println("Improving weather on the way!");
		} else if (currentPressure == lastPressure) {
			System.out.println("More of the same");
		} else if (currentPressure < lastPressure) {
			System.out.println("Watch out for cooler, rainy weather");
		}
	}
}


package com.observers;

import java.util.Observable;
import java.util.Observer;

import com.interfaces.DisplayElement;
import com.theme.WeatherData;

public class StatisticsDisplay implements Observer, DisplayElement {
	private float maxTemp = 0.0f;
	private float minTemp = 200;
	private float tempSum= 0.0f;
	private int numReadings;

	public StatisticsDisplay(Observable observable) {
		observable.addObserver(this);
	}

	public void update(Observable observable, Object arg) {
		if (observable instanceof WeatherData) {
			WeatherData weatherData = (WeatherData)observable;
			float temp = weatherData.getTemperature();
			tempSum += temp;
			numReadings++;

			if (temp > maxTemp) {
				maxTemp = temp;
			}

			if (temp < minTemp) {
				minTemp = temp;
			}

			display();
		}
	}

	public void display() {
		System.out.println("Avg/Max/Min temperature = " + (tempSum / numReadings)
				+ "/" + maxTemp + "/" + minTemp);
	}
}


package com.test;

import com.observers.CurrentConditionsDisplay;
import com.observers.ForecastDisplay;
import com.observers.StatisticsDisplay;
import com.theme.WeatherData;

public class WeatherStation {
	public static void main(String[] args) {
		WeatherData weatherData = new WeatherData();
		new CurrentConditionsDisplay(weatherData);
		new StatisticsDisplay(weatherData);
		new ForecastDisplay(weatherData);

		weatherData.setMeasurements(80, 65, 30.4f);
		weatherData.setMeasurements(82, 70, 29.2f);
		weatherData.setMeasurements(78, 90, 29.2f);
	}

}


运行结果为:
Forecast: Improving weather on the way!
Avg/Max/Min temperature = 80.0/80.0/80.0
Current conditions: 80.0F degrees and 65.0% humidity
Forecast: Watch out for cooler, rainy weather
Avg/Max/Min temperature = 81.0/82.0/80.0
Current conditions: 82.0F degrees and 70.0% humidity
Forecast: More of the same
Avg/Max/Min temperature = 80.0/82.0/78.0
Current conditions: 78.0F degrees and 90.0% humidity

运行方式和第一种实现方式差不多,只不过Observable类帮主题类实现了很多方法,主题类直接用这些方法即可。优缺点:由于这里的主题是继承Observable类,而不是实现接口,这就缺少很多弹性,这限制了主题类的使用和复用
分享到:
评论

相关推荐

    观察者模式Observer

    观察者模式(Observer)是设计模式中的一种行为模式,它定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并被自动更新。这种模式在软件开发中广泛应用于事件处理和实时...

    观察者模式observer

    观察者模式(Observer Pattern)是设计模式中的一种行为模式,它定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并被自动更新。这种模式常用于实现事件驱动编程或者...

    设计模式- 观察者模式 Observer Pattern详解

    首先,观察者模式的经典实现涉及两个主要对象:主题(Subject)和观察者(Observer)。主题维护一组观察者,并在状态变化时通知它们。观察者则订阅主题,以便在主题状态改变时接收通知。在C#中,这通常通过接口来...

    swift-Swiftµframework实现观察者模式Observerpattern

    Swift µframework 实现观察者模式Observer pattern

    设计模式之观察者模式(Observer Pattern)

    "ObserverPattern(订阅模式)3.zip"中的代码可能进一步阐述了观察者模式,这里的“订阅”一词可能意味着用户可以订阅特定的主题,只有当这些主题的状态改变时,用户才会收到通知。这与传统的观察者模式类似,但更加...

    设计模式C++学习之观察者模式(Observer)

    观察者模式(Observer)是软件设计模式中的一种行为模式,它定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并被自动更新。这种模式在C++中广泛应用,特别是在需要...

    设计模式之观察者模式(Observer)

    观察者模式(Observer)是软件设计模式中的一种行为模式,其主要目的是在对象之间建立一种松散耦合的关系,使得当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。这种模式广泛应用于事件驱动...

    观察者模式(Observer Pattern) 1. 什么是观察者模式? 2. 为什么需要观察者模式? 3. 观察者模式的核心概念 4. 观察者模式的结构 5. 观察者模式的基本实现 简单的气象站示例

    观察者模式(Observer Pattern) 1. 什么是观察者模式? 2. 为什么需要观察者模式? 3. 观察者模式的核心概念 4. 观察者模式的结构 5. 观察者模式的基本实现 简单的气象站示例 6. 观察者模式的进阶实现 推模型 vs 拉...

    观察者模式(Observer)

    观察者模式(Observer)是一种行为设计模式,它允许你定义一个订阅机制,可以在对象状态变化时通知多个“观察”该对象的其他对象。这个模式在软件工程中扮演着重要角色,尤其是在事件驱动编程和发布/订阅系统中。...

    观察者(Observer)模式

    观察者模式的核心概念是主体(Subject)和观察者(Observer)。主体是被观察的对象,它维护了一个观察者列表,并提供了添加、删除观察者以及通知所有观察者的接口。观察者关注主体的状态变化,并在主体状态改变时...

    观察者模式(Observer)

    观察者模式(Observer)是一种行为设计模式,它允许你定义一个订阅机制,可以在对象状态变化时通知多个“观察”该对象的其他对象。这个模式在软件工程中广泛应用于事件驱动编程,例如用户界面组件的交互或者系统状态的...

    观察者模式,Observer

    观察者模式(Observer Pattern)是设计模式中的一种行为模式,它定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并被自动更新。这种模式常用于实现事件驱动的系统或者...

    C++设计模式之观察者模式(Observer)

    观察者模式通常的叫法叫做订阅-发布模式,类似于报刊杂志的订阅,观察者和被观察者就是读者和邮局的关系,读者先要在邮局订阅想要的报刊,当报刊发行时,邮局会将报刊邮寄到读者家里。观察者(Observer)和被观察者...

    [行为模式]head first 设计模式之观察者模式(observer)

    观察者模式(Observer Pattern)是设计模式中的一种行为模式,它定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。这种模式在软件开发中广泛应用于事件驱动...

    C#面向对象设计模式纵横谈(19):(行为型模式) Observer 观察者模式 (Level 300)

    **C#面向对象设计模式纵横谈(19)**:**观察者模式**(Observer Pattern)是行为型模式的一种,它在软件工程中扮演着至关重要的角色。观察者模式是一种设计模式,它定义了对象之间的一对多依赖关系,当一个对象的状态...

    Observer 观察者模式 示例 源码 ----设计模式

    观察者模式 概述 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。 适用性 1.当一个抽象模型有两个方面,其中一个方面依赖于另一方面。 将这二者封装...

    使用MFC实现观察者模式(Observer)同时兼顾多窗口之间传值

    观察者模式(Observer)是一种设计模式,它定义了对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。在MFC(Microsoft Foundation Classes)框架中,我们可以...

    android Observer(观察者模式)_案例祥解.pdf

    观察者模式详解 观察者模式是23种设计模式中的一种,尤其是在软件设计过程中体现的更是立足无穷。本文将详细讲解观察者模式的概念和实现,通过代码注释来解释各个组件的作用。 一、观察者模式的定义 观察者模式是...

    observer观察者模式

    观察者模式(Observer Pattern)是一种行为设计模式,它允许你定义一个订阅机制,可以在对象状态改变时通知多个“观察”该对象的其他对象。在软件工程中,这常用于实现事件驱动编程,使得系统能够及时响应变化。 在...

Global site tag (gtag.js) - Google Analytics