一、概述:
1、定义:观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。
2、结构图:
public interface Subject {void registerObserver(Observer observer);void unregisterObserver(Observer observer);void notifyObservers();
}
public interface Observer {void update();
}
实现
import java.util.ArrayList;
import java.util.List;public class ConcreteSubject implements Subject {private List<Observer> observers = new ArrayList<>();private int state;public int getState() {return state;}public void setState(int state) {this.state = state;notifyObservers();}@Overridepublic void registerObserver(Observer observer) {observers.add(observer);}@Overridepublic void unregisterObserver(Observer observer) {observers.remove(observer);}@Overridepublic void notifyObservers() {for (Observer observer : observers) {observer.update();}}
}
public class ConcreteObserver implements Observer {private int observerState;private ConcreteSubject subject;public ConcreteObserver(ConcreteSubject subject) {this.subject = subject;this.subject.registerObserver(this);}@Overridepublic void update() {observerState = subject.getState();System.out.println("Observer state updated: " + observerState);}
}
调用
public class Main {public static void main(String[] args) {ConcreteSubject subject = new ConcreteSubject();ConcreteObserver observer1 = new ConcreteObserver(subject);ConcreteObserver observer2 = new ConcreteObserver(subject);subject.setState(10);// 输出:// Observer state updated: 10// Observer state updated: 10subject.setState(20);// 输出:// Observer state updated: 20// Observer state updated: 20subject.unregisterObserver(observer2);subject.setState(30);// 输出:// Observer state updated: 30}
}