定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于他的对象都得到通知并被自动更新。
- import java.util.ArrayList;
- import java.util.List;
-
- // 观察者接口
- interface Observer {
- void update();
- }
-
- // 目标类
- class Subject {
- private List
observers = new ArrayList<>(); -
- // 注册观察者
- public void registerObserver(Observer observer) {
- observers.add(observer);
- }
-
- // 删除观察者
- public void removeObserver(Observer observer) {
- observers.remove(observer);
- }
-
- // 当状态发生改变时通知观察者
- public void notifyObservers() {
- for (Observer observer : observers) {
- observer.update();
- }
- }
- }
-
- // 具体目标类
- class ConcreteSubject extends Subject {
- private int state;
-
- public int getState() {
- return state;
- }
-
- public void setState(int state) {
- this.state = state;
- notifyObservers(); // 通知观察者状态改变
- }
- }
-
- // 具体观察者类
- class ConcreteObserver implements Observer {
- private ConcreteSubject subject;
-
- public ConcreteObserver(ConcreteSubject subject) {
- this.subject = subject;
- this.subject.registerObserver(this); // 注册观察者
- }
-
- @Override
- public void update() {
- System.out.println("Observer updated, new state: " + subject.getState());
- }
- }
-
- // 测试
- public class ObserverPatternExample {
- public static void main(String[] args) {
- ConcreteSubject subject = new ConcreteSubject();
- ConcreteObserver observer1 = new ConcreteObserver(subject);
- ConcreteObserver observer2 = new ConcreteObserver(subject);
-
- subject.setState(10);
- subject.setState(20);
- }
- }