一、概述:
1、定义:观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。
2、结构图:
public interface Subject {
void registerObserver(Observer observer);
void unregisterObserver(Observer observer);
void notifyObservers();
}
public interface Observer {
void update();
}
实现文章来源:https://www.toymoban.com/news/detail-676092.html
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();
}
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
@Override
public void unregisterObserver(Observer observer) {
observers.remove(observer);
}
@Override
public 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);
}
@Override
public void update() {
observerState = subject.getState();
System.out.println("Observer state updated: " + observerState);
}
}
调用文章来源地址https://www.toymoban.com/news/detail-676092.html
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: 10
subject.setState(20);
// 输出:
// Observer state updated: 20
// Observer state updated: 20
subject.unregisterObserver(observer2);
subject.setState(30);
// 输出:
// Observer state updated: 30
}
}
到了这里,关于设计模式(11)观察者模式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!