概述:
定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
适用性:
1.当一个抽象模型有两个方面,其中一个方面依赖于另一方面。 将这二者封装在独立的对象中以使它们可以各自独立地改变和复用。 2.当对一个对象的改变需要同时改变其它对象,而不知道具体有多少对象有待改变。 3.当一个对象必须通知其它对象,而它又不能假定其它对象是谁。
我们以天气预报的服务为例,安卓和诺基亚购买天气预报的服务,也可以停用服务:
天气预报主体的接口:
public interface Subject {
public void zhuce(Observer observer);
public void remove(Observer observer);
public void tongzhi();
}
天气预报的实现类:
public class WeatherData implements Subject {
private int low;
private int hight;
private String weather;
private List<Observer> list = new ArrayList<Observer>();
public void setData(int low, int hight, String weather) {
this.low = low;
this.hight = hight;
this.weather = weather;
tongzhi();
}
public int getLow() {
return low;
}
public int getHight() {
return hight;
}
public String getWeather() {
return weather;
}
public void zhuce(Observer observer) {
if (!list.contains(observer)) {
list.add(observer);
}
}
public void remove(Observer observer) {
if (list.contains(observer)) {
list.remove(observer);
}
}
public void tongzhi() {
for (Observer o : list) {
o.update(getLow(), getHight(), getWeather());
}
}
}
观察者的接口:
public interface Observer {
void remove();
void update(int low, int hight, String weather);
}
观察者的实现类:
public class Android implements Observer {
private Subject subject;
public Android() {
}
public Android(Subject subject) {
this.subject = subject;
this.subject.zhuce(this);
}
public void update(int low, int hight, String weather) {
System.out.println("android" + low + "" + hight + weather);
}
public void remove() {
subject.remove(this);
}
}
public class Nokia implements Observer{
private Subject subject;
public Nokia(){}
public Nokia(Subject subject){
this.subject = subject;
this.subject.zhuce(this);
}
public void update(int low, int hight, String weather) {
System.out.println("nokia:"+low+"-"+hight+"-"+weather);
}
public void remove(){
subject.remove(this);
}
}
测试类:
public class Test {
public static void main(String[] args) {
WeatherData wd = new WeatherData();
wd.setData(1, 22, "晴朗");
Android a = new Android(wd);
wd.tongzhi();
a.remove();
Nokia n = new Nokia(wd);
n.remove();
wd.tongzhi();
}
}