观察者模式代码
import java.util.Observable;
public class Product extends Observable{
private double price=2.0;
public double getPrice() {
return price;
}
public void setPrice(double price) {
System.out.println("setPrice");
this.setChanged();
this.notifyObservers(price);//找2个方法次序不能换
this.price = price;
}
}
public class PriceObserver implements Observer {
private double price;
public PriceObserver(double price) {
this.price = price;
}
public void update(Observable ob, Object obj) {
double pri = (Double) obj;// 注意代码 解箱
if (pri > 1.1 * price) {
System.out.println("通货膨胀");
} else {
System.out.println("物价正常");
}
this.price=pri;
}
public static void main(String[] args) {
Product p=new Product();
PriceObserver po=new PriceObserver(p.getPrice());
p.addObserver(po);
p.setPrice(3.0);
p.setPrice(3.1);
}
}