1、房子类,我们让他继承Observable,并在价格改变时super父类的两个方法(红色标注)。
package demo3_observer;
import java.util.Observable;
public class House extends Observable{
private int price;
public House(int price) {
super();
this.price = price;
}
public void setPrice(int price) {
super.setChanged();
super.notifyObservers(price);
this.price = price;
}
public int getPrice() {
return this.price;
}
public String toString() {
return "房子价格为:" + this.price;
}
}
2、观察者类,在这里我们可以把这些观察者作为需要购买房子的人。
package demo3_observer;
import java.util.Observable;
import java.util.Observer;
public class HousePriceObserver implements Observer {
private String name;
public HousePriceObserver(String name) {
super();
this.name = name;
}
public void update(Observable o, Object arg) {
if(arg instanceof Integer) {
System.out.println(this.name + "观察到价格更改为:" + ((Integer)arg).intValue());
}
}
}
3、demo类,我们把每一个房价观察者分别加入到房子中
package demo3_observer;
public class ObserDemo01 {
/**
* @param args
*/
public static void main(String[] args) {
House h = new House(1000000);
HousePriceObserver h1 = new HousePriceObserver("A");
HousePriceObserver h2 = new HousePriceObserver("B");
HousePriceObserver h3 = new HousePriceObserver("C");
h.addObserver(h3);
h.addObserver(h2);
h.addObserver(h1);
System.out.println(h);
h.setPrice(2000000);
System.out.println(h);
}
}
4、总结:每一个观察者类都需要实现Observer接口
public interface Observer {
void update(Observable o, Object arg);
}