观察者模式
当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)
比如,当一个对象被修改时,则会自动通知它的依赖对象,观察者模式属于行为型模式。
使用
在java中实现观察者模式需要用到java.util包中提供的Observable类和Observer接口,java已经给我们提供好类使用。Observable可以查看java源码,下面是Observer接口:
/**
* {@code Observer} is the interface to be implemented by objects that
* receive notification of updates on an {@code Observable} object.
*
* @see Observable
*/
public interface Observer {
/**
* This method is called if the specified {@code Observable} object's
* {@code notifyObservers} method is called (because the {@code Observable}
* object has been updated.
*
* @param observable
* the {@link Observable} object.
* @param data
* the data passed to {@link Observable#notifyObservers(Object)}.
*/
void update(Observable observable, Object data);
}
实例
古董被观察,观察者为people用来观察古董价钱波动
- 被观察者需要继承Observable
- 维护内部数据即可
public class Antique extends Observable {
private float mPrice;// 价钱
public Antique(float price) {
this.mPrice = price;
}
public float getPrice() {
return this.mPrice;
}
public void setPrice(float price) {
super.setChanged();
super.notifyObservers(price);// 价格被改变
this.mPrice = price;
}
public String toString() {
return "古董价格为:" + this.mPrice;
}
}
观察者实现Observer接口,重写update方法即可
public class People implements Observer{
private String name;
public People(String name) {
this.name = name;
}
@Override
public void update(Observable observable, Object data) {
Log.e("","People update() -> update name:"+ this.name + ",price:"+ ((Float)data).floatValue());
}
}
主函数调用
Antique house = new Antique(1222f);
People p1 = new People("p1");
People p2 = new People("p2");
People p3 = new People("p3");
house.addObserver(p1);
house.addObserver(p2);
house.addObserver(p3);
Log.e("", house+""); // 输出价格
house.setPrice(111f);
Log.e("", house+""); // 输出价格
网友评论