定义了一种一对多的依赖关系,让多个观察者对象同时监听某一主题对象,在它的状态发生变化时,会通知所有的观察者.
import java.util.ArrayList;
import java.util.List;
/**
* 内容提供者
* @author fan
*
*/
public class Subject {
private List<Observe> observers = new ArrayList<>();
private int State;
public int getState() {
return State;
}
public void setState(int state) {
State = state;
notificationAll();
}
public void attach(Observe observer) {
observers.add(observer);
}
private void notificationAll() {
// TODO Auto-generated method stub
for (Observe observe : observers) {
observe.update();
}
}
}
/**
* 观察者抽象类
* @author fan
*
*/
public abstract class Observe {
protected Subject subject;
public abstract void update();
}
/**
* 观察实体类
* @author fan
*
*/
public class Observer extends Observe {
Observer(Subject subject) {
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
// TODO Auto-generated method stub
System.out.println(this.subject.getState());
}
}
//测试
public class Test {
public static void main(String[] args) {
Subject subject= new Subject();
new Observer(subject);
subject.setState(1);
subject.setState(2);
subject.setState(3);
}
}
//res
1
2
3