import java.util.ArrayList; import java.util.List; abstract class Observer { public abstract void Update(); } class Subject { private List<Observer> observers = new ArrayList<Observer>(); 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(); } }