设计模式-观察者模式
//被监听的类继承Observable类
public class Product extends Observable{
private String name;
private float price;
public void setName(String name){
this.name = name;
setChanged();
notifyObservalble(name);
}
public String getName(){
return name;
}
public void setPrice(float price){
this.price = price;
setChanged();
notifyObservables(new Float(price));
}
public Float getPrice(){
return price;
}
}
观察者实现Observer
实现update方法
//价格的观察者
NameObserver类
private String name;
public void update(Observable o,Object arg){
if(arg instanceof String){
name = (String)arg;
System.out.println("name change to:"+name);
}
}
//价格的观察者
PriceObserver类
private Float price;
public void update(Observable o,Object arg){
if(arg instanceof String){
price= (float)arg;
System.out.println("name change to:"+price);
}
}
测试类
public static void main(String[] args){
Product product = new Product();
NameObserver nameObserver = new NameObserver();
PriceObserver priceObserver = new PriceObserver();
product.addObserver(nameObserver);
product.addObserver(priceObserver);
product.setName("apple");
product.setPrice("3.0");
product.notifyObservers();
}