// Subject-目标(主题) public abstract class Subject { public List<Observer> observers; public Subject() { observers = new ArrayList<Observers>(); } public void attach(Observer observer) { observers.add(observer); } public boolean detach(Observer observer) { return observers.remove(observer); } public abstract void notify(); }
// Observer-观察者 -> 定义共同约定的接口 public interface Observer { public void update(); }
// ConcreteSubject-具体目标(主题) public class ConcreteSubject extends Subject { public void notify(String text) { for (Observer observer: observers) { observer.update(text); } } }
// ConcreteObserver-具体观察者 // 观察者1 public class ConcreteObserver1 implements Observer { private ConcreteSubject concreteSubject; public ConcreteObserver1(ConcreteSubject concreteSubject) { this.concreteSubject = concreteSubject; } public void update(String text) { display(text); } public void display(String text) { System.out.println("ConcreteObserver1 get message: " + text); } }
// 观察者2 public class ConcreteObserver2 implements Observer { private ConcreteSubject concreteSubject; public ConcreteObserver2(ConcreteSubject concreteSubject) { this.concreteSubject = concreteSubject; } public void update(String text) { display(text); } public void display(String text) { System.out.println("ConcreteObserver2 get message: " + text + ", also can individuation."); } }
// 测试类 public class Test { public static void main(String[] args) { ConcreateSubject subject = new ConcreteSubject(); Observer observer1 = new ConcreteObserver1(); Observer observer2 = new ConcreteObserver2(); // 向目标(主体)注册观察者 subject.attach(observer1); subject.attach(observer2); // 向已注册的观察者发送消息 subject.notify("test message - A"); subject.notify("test message - B"); } }