import java.util.ArrayList;
public abstract class Observable {
private ArrayList<Observer> observers = new ArrayList();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void notifyObservers(Object object) {
for (Observer observer : observers) {
observer.update(this, object);
}
}
}
public interface Observer {
void update(Observable observable, Object object);
}
Observer是观察者。Observable是被观察者。
public class Observer1 implements Observer {
@Override
public void update(Observable observable, Object object) {
System.out.println("Observer1 update:" + object + "," + observable.toString());
}
}
public class Observer2 implements Observer {
@Override
public void update(Observable observable, Object object) {
System.out.println("Observer2 update:" + object + "," + observable.toString());
}
}
public class Test {
public static void main(String[] args) {
try {
Test test = new Test();
} catch (Exception e) {
e.printStackTrace();
}
}
private class Target extends Observable {
}
public Test() {
// 被观察者。
Observable target = new Target();
// 观察者。
Observer observer1 = new Observer1();
Observer observer2 = new Observer2();
target.addObserver(observer1);
target.addObserver(observer2);
int count = 0;
while (true) {
target.notifyObservers(count++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
输出:
Observer1 update:0,Test$Target@15db9742
Observer2 update:0,Test$Target@15db9742
Observer1 update:1,Test$Target@15db9742
Observer2 update:1,Test$Target@15db9742
Observer1 update:2,Test$Target@15db9742
Observer2 update:2,Test$Target@15db9742
Observer1 update:3,Test$Target@15db9742
Observer2 update:3,Test$Target@15db9742
Observer1 update:4,Test$Target@15db9742
Observer2 update:4,Test$Target@15db9742
Observer1 update:5,Test$Target@15db9742
Observer2 update:5,Test$Target@15db9742
Observer1 update:6,Test$Target@15db9742
Observer2 update:6,Test$Target@15db9742
......