🔍目的
🔍解释
真实世界例子
通俗描述
维基百科
编程示例
首先创建天气观察者的接口以及我们的种族,兽人和霍比特人。
public interface WeatherObserver {
void update(WeatherType currentWeather);
}
@Slf4j
public class Orcs implements WeatherObserver {
@Override
public void update(WeatherType currentWeather) {
LOGGER.info("The orcs are facing " + currentWeather.getDescription() + " weather now");
}
}
@Slf4j
public class Hobbits implements WeatherObserver {
@Override
public void update(WeatherType currentWeather) {
switch (currentWeather) {
LOGGER.info("The hobbits are facing " + currentWeather.getDescription() + " weather now");
}
}
创建一个动态变化的天气:
@Slf4j
public class Weather {
private WeatherType currentWeather;
private final List<WeatherObserver> observers;
public Weather() {
observers = new ArrayList<>();
currentWeather = WeatherType.SUNNY;
}
public void addObserver(WeatherObserver obs) {
observers.add(obs);
}
public void removeObserver(WeatherObserver obs) {
observers.remove(obs);
}
/**
* Makes time pass for weather.
*/
public void timePasses() {
var enumValues = WeatherType.values();
currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length];
LOGGER.info("The weather changed to {}.", currentWeather);
notifyObservers();
}
private void notifyObservers() {
for (var obs : observers) {
obs.update(currentWeather);
}
}
}
执行示例:
var weather = new Weather();
weather.addObserver(new Orcs());
weather.addObserver(new Hobbits());
weather.timePasses();
// The weather changed to rainy.
// The orcs are facing rainy weather now
// The hobbits are facing rainy weather now
weather.timePasses();
// The weather changed to windy.
// The orcs are facing windy weather now
// The hobbits are facing windy weather now
weather.timePasses();
// The weather changed to cold.
// The orcs are facing cold weather now
// The hobbits are facing cold weather now
weather.timePasses();
// The weather changed to sunny.
// The orcs are facing sunny weather now
// The hobbits are facing sunny weather now
🔍类图
🔍扩展延伸
观察者模式在kafka client consumer中的使用:
大致逻辑:
依赖关系:
RequestFutureListener部分代码:
public interface RequestFutureListener<T> {
void onSuccess(T value);
void onFailure(RuntimeException e);
}
RequestFuture部分代码:
public class RequestFuture<T> implements ConsumerNetworkClient.PollCondition {
private static final Object INCOMPLETE_SENTINEL = new Object();
private final AtomicReference<Object> result = new AtomicReference<>(INCOMPLETE_SENTINEL);
private final ConcurrentLinkedQueue<RequestFutureListener<T>> listeners = new ConcurrentLinkedQueue<>();
private final CountDownLatch completedLatch = new CountDownLatch(1);
public void complete(T value) {
try {
if (value instanceof RuntimeException)
throw new IllegalArgumentException("The argument to complete can not be an instance of RuntimeException");
if (!result.compareAndSet(INCOMPLETE_SENTINEL, value))
throw new IllegalStateException("Invalid attempt to complete a request future which is already complete");
fireSuccess();
} finally {
completedLatch.countDown();
}
}
//遍历listener并调用其success时的方法
private void fireSuccess() {
T value = value();
while (true) {
RequestFutureListener<T> listener = listeners.poll();
if (listener == null)
break;
listener.onSuccess(value);
}
}
//遍历listener并调用其fail时的方法
private void fireFailure() {
RuntimeException exception = exception();
while (true) {
RequestFutureListener<T> listener = listeners.poll();
if (listener == null)
break;
listener.onFailure(exception);
}
}
//增加listener
public void addListener(RequestFutureListener<T> listener) {
this.listeners.add(listener);
if (failed())
fireFailure();
else if (succeeded())
fireSuccess();
}
🔍适用场景
在下面任何一种情况下都可以使用观察者模式
🔍Ending
观察者模式(Observer Pattern)是一种行为设计模式,它定义了一种一对多的依赖关系,使得当一个对象的状态发生变化时,所有依赖于它的对象都会得到通知并自动更新。
在观察者模式中,通常包含以下几个角色:
希望本文能够帮助读者更深入地理解观察者模式,并在实际项目中发挥其优势。谢谢阅读!
希望这份博客草稿能够帮助到你。如果有其他需要修改或添加的地方,请随时告诉我。