观察者模式避免了各组件之间紧密耦合,它将观察者和被观察的对象分离开来,一个对象添加一个方法(即观察者注册自己)使本身变得可观察,当可观察的对象更改时,它会将消息发送到已注册的观察者,这些观察者收到消息后执行的操作与可观察的对象无关,这种模式使得对象之间可以相互对话,而不用了解原因;
下面我们来看一个列子
package com.ys.observer;
import java.util.ArrayList;
/**
* 利用观察者模式实现一个天气预报,当天气发生更改时,通知观察者
* @author cena
*
*/
interface Weather{
public void registObserver(Observer observer);
public void removeObserver(Observer observer);
public void notiyAll();
}
interface Observer{
public void update(int t);
}
class WeatherImpl implements Weather{
ArrayList<Observer>list=new ArrayList<Observer>();
private int temperature;
@Override
public void registObserver(Observer observer) {
list.add(observer);
}
@Override
public void removeObserver(Observer observer) {
list.remove(observer);
}
@Override
public void notiyAll() {
for (int i = 0; i < list.size(); i++) {
list.get(i).update(temperature);
}
}
public void setTemperature(int n) {
this.temperature=n;
notiyAll();
}
public int getTemperature() {
return temperature;
}
}
class OberverImpl01 implements Observer {
private int temperature;
public OberverImpl01(Weather weather) {
weather.registObserver(this);
}
public void update(int t) {
this.temperature=t;
disPlay();
}
public void disPlay() {
System.out.println("01temperature is "+temperature);
}
}
class OberverImpl02 implements Observer {
private int temperature;
public OberverImpl02(Weather weather) {
weather.registObserver(this);
}
@Override
public void update(int t) {
this.temperature=t;
disPlay();
}
public void disPlay() {
System.out.println("02temperature is "+temperature);
}
}
public class Test {
public static void main(String[] args) {
WeatherImpl weather=new WeatherImpl();
Observer observer01=new OberverImpl01(weather);
Observer observer02=new OberverImpl02(weather);
weather.setTemperature(28);
}
}