标签:
定义了对象间的一种一对多依赖关系,使得每当一个对象改变状态,则所有依赖于它的对象都会得到通知并被自动更新。
Observer模式提供给关联对象一种同步通信的手段,使某个对象与依赖它的其他对象之间保持状态同步。
java提供Obeservable类和Observer接口。
比如购房,购房者是观察者,而房价是被观察者,房价的变化是被观察者所关注的。
/** * 被观察者 * @author soyoungboy * */ public 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; } @Override public String toString() { return "House [price=" + price + "]"; } }
/** * 房价观察者 * @author soyoungboy * */ public class HouseObserver implements Observer { //购房者名称 private String name; public HouseObserver(String name) { this.name = name; } @Override public void update(Observable o, Object arg) { if (arg instanceof Float) { System.out.println("name 观察到房价变化为:"+((Float)arg).floatValue()); } } }
public class Test { public static void main(String[] args) { House house = new House(10000); HouseObserver houseObserver = new HouseObserver("购房者A"); HouseObserver houseObserver1 = new HouseObserver("购房者B"); HouseObserver houseObserver2 = new HouseObserver("购房者C"); //添加房价的监听者 house.addObserver(houseObserver); house.addObserver(houseObserver1); house.addObserver(houseObserver1); System.out.println(house.toString()); house.setPrice(20000); System.out.println(house.toString()); house.setPrice(30000); System.out.println(house.toString()); } }
结果为:
House [price=10000.0] name 观察到房价变化为:20000.0 name 观察到房价变化为:20000.0 House [price=20000.0] name 观察到房价变化为:30000.0 name 观察到房价变化为:30000.0 House [price=30000.0]
标签:
原文地址:http://www.cnblogs.com/androidsuperman/p/4744805.html