十四、行为型(观察者模式)

时间:2024-10-17 07:21:21
// 观察者接口 interface Observer { void update(String message); } // 具体观察者A class ConcreteObserverA implements Observer { private String name; public ConcreteObserverA(String name) { this.name = name; } @Override public void update(String message) { System.out.println(name + " 收到通知: " + message); } } // 具体观察者B class ConcreteObserverB implements Observer { private String name; public ConcreteObserverB(String name) { this.name = name; } @Override public void update(String message) { System.out.println(name + " 收到通知: " + message); } } // 被观察者接口 interface Subject { void registerObserver(Observer observer); void removeObserver(Observer observer); void notifyObservers(String message); } // 具体主题 class ConcreteSubject implements Subject { private List<Observer> observers = new ArrayList<>(); @Override public void registerObserver(Observer observer) { observers.add(observer); } @Override public void removeObserver(Observer observer) { observers.remove(observer); } @Override public void notifyObservers(String message) { for (Observer observer : observers) { observer.update(message); } } } // 客户端代码 public class ObserverPatternDemo { public static void main(String[] args) { ConcreteSubject subject = new ConcreteSubject(); Observer observer1 = new ConcreteObserverA("观察者1"); Observer observer2 = new ConcreteObserverB("观察者2"); subject.registerObserver(observer1); subject.registerObserver(observer2); // 通知所有观察者 subject.notifyObservers("主题状态发生变化"); // 移除观察者1,之后再次通知 subject.removeObserver(observer1); subject.notifyObservers("第二次状态变化"); } }