被观察者类继承 java.util.Observable,观察者类实现接口 java.util.Observer。被观察者在需要的方法中调用父类Observable的 setChanged() 方法和 notifyObservers(Object obj) 通知观察者。观察者类实现接口 Observer 的方法 update(Observable o, Object arg).
例:
public class Product extends Observable { // 被观察者
private String name;
private float price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
// 设置变化点
setChanged();
notifyObservers(name);
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
// 设置变化点
setChanged();
notifyObservers(new Float(price));
}
// 以下可以是数据库更新 插入命令.
public void saveToDb() {
}
}
public class NameObserver implements Observer { // 观察者1
private String name = null;
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
if (arg instanceof String) {
name = (String) arg;
// 产品名称改变值在name中
System.out.println("NameObserver :name changet to " + name);
}
}
}
public class PriceObserver implements Observer { // 观察者2
private float price = 0;
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
if (arg instanceof Float) {
price = ((Float) arg).floatValue();
System.out.println("PriceObserver :price changet to " + price);
}
}
}
下面是测试:
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Product product = new Product();
product.addObserver(new NameObserver());
product.addObserver(new PriceObserver());
product.setName("book");
product.setPrice(66f);
}
}
将会打印出
NameObserver :name changet to book
PriceObserver :price changet to 66.0