观察者设计模式

本章目标
了解观察者设计模式的作用
掌握Observable类Observer接口的使用

 

观察者设计模式
“现在很多的购房者都在关注着房子的价格变化,每当房子价格变化的时候,所有的购房者都可以观察得到”,实际上以上的购房者都属于观察者,他们都在关注着房子的价格。
观察者设计模式
 

观察者模式实现
在java.util包中提供了Observable类和Observer接口,使用它们就可以完成观察者模式了。在需要被观察的类必须继承Observable类。

 

Observable类的常用方法
观察者设计模式
 

import java.util.Observable;
import java.util.Observer;
class House extends Observable{
	private float price;
	public House(float price) {
		this.price = price;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		super.setChanged();//设置变化点
		super.notifyObservers(price);//通知所有观察者价格改变
		this.price=price;
	}
	public String toString(){
		return "房子价格为:"+this.price;
	}
}
class HousePriceObser implements Observer{
	private String name;
	public HousePriceObser(String name) {
		this.name = name;
	}
	public void update(Observable obj, Object arg){
		if(arg instanceof Float){//判断参数类型
			System.out.print(this.name +"观察到价格更改为:");
			System.out.println(((Float)arg).floatValue());
		}
	}
}
public class ObserDemo01 {
	public static void main(String[] args) {
		House h = new House(1000000);
		HousePriceObser hpo1 = new HousePriceObser("购房者 A");
		HousePriceObser hpo2 = new HousePriceObser("购房者 B");
		HousePriceObser hpo3 = new HousePriceObser("购房者 C");
		h.addObserver(hpo1);//加入观察者
		h.addObserver(hpo2);//加入观察者
		h.addObserver(hpo3);//加入观察者
		System.out.println(h);//输出房子价格
		h.setPrice(666666);//修改房子价格
		System.out.println(h);//输出房子价格
	}
/* 结果:
 * 房子价格为:1000000.0
 * 购房者 C观察到价格更改为:666666.0
 * 购房者 B观察到价格更改为:666666.0
 * 购房者 A观察到价格更改为:666666.0
 * 房子价格为:666666.0
 * */
}

 

 

 

 

你可能感兴趣的:(设计模式)