* 把所有观察者加入一个列表 * 当某个条件满足时 * 遍历列表,通知每一个观察者 (调用每个观察者的update回调函数) import java.util.ArrayList; import java.util.List; abstract class Observer { public abstract void Update(); } class Subject { private List observers = new ArrayList(); public void Attach(Observer observer) { observers.add(observer); } public void Detach(Observer observer) { observers.remove(observer); } public void Notify() { for (Observer o : observers) { o.Update(); } } } class ConcreteObserver extends Observer{ private String name = ""; public ConcreteObserver(String name){this.name = name;} @Override public void Update() { System.out.println(name); } } public class Program { public static void main(String[] args) { // 具体主题角色通常用具体自来来实现 Subject subject = new Subject(); subject.Attach(new ConcreteObserver("A")); subject.Attach(new ConcreteObserver("B")); subject.Attach(new ConcreteObserver("C")); if(true) // 当某个条件触发时,通知所有观察者 subject.Notify(); } }