本文是针对房价变动的观察者模式实现,使用java写了一个简单的demo,直接上代码
package observer;
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 HousePriceObserver implements Observer{
private String name;
public HousePriceObserver(String name){
this.name = name;
}
@Override
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
if(arg instanceof Float){
System.out.print(this.name + "观察到价格更改为: ");
System.out.println(((Float) arg).floatValue());
}
}
}
public class ObserDemo {
public static void main(String[] args) {
House h = new House(1000000);
HousePriceObserver hpo1 = new HousePriceObserver("购房者A");
HousePriceObserver hpo2 = new HousePriceObserver("购房者B");
HousePriceObserver hpo3 = new HousePriceObserver("购房者C");
h.addObserver(hpo1);
h.addObserver(hpo2);
h.addObserver(hpo3);
System.out.println(h);
h.setPrice(666666);
System.out.println(h);
}
}