如何使用Java中的观察者模式?
该问题的明确答案是推荐使用自定义观察者接口实现观察者模式。1. 虽然Java提供了Observable和Observer,但前者是类且已弃用,缺乏灵活性;2. 现代推荐做法是定义函数式Observer
The Observer pattern in Java is a behavioral design pattern where an object (called the subject) maintains a list of dependents (called observers) that are notified automatically when the subject changes state. Java provides built-in support for this pattern via the java.util.Observable
class and java.util.Observer
interface — although they are deprecated since Java 9, understanding them helps grasp the concept. We’ll cover both the legacy approach and the modern, recommended way using custom interfaces or functional programming.

1. Using the Legacy Observable
and Observer
(Not Recommended)
Even though it's deprecated, here’s how it used to work:
import java.util.Observable; import java.util.Observer; // Subject (data source) class WeatherStation extends Observable { private float temperature; public void setTemperature(float temperature) { this.temperature = temperature; setChanged(); // Must call this before notifyObservers notifyObservers(temperature); // Send update } public float getTemperature() { return temperature; } } // Observer (subscriber) class Display implements Observer { private String name; public Display(String name) { this.name = name; } @Override public void update(Observable observable, Object arg) { if (observable instanceof WeatherStation) { float temp = (Float) arg; System.out.println(name " display: Temperature updated to " temp "°C"); } } } // Usage public class ObserverDemo { public static void main(String[] args) { WeatherStation station = new WeatherStation(); Display phoneDisplay = new Display("Phone"); Display tvDisplay = new Display("TV"); station.addObserver(phoneDisplay); station.addObserver(tvDisplay); station.setTemperature(25.5f); // Triggers notifications station.setTemperature(30.0f); } }
⚠️ Note:
Observable
is a class, not an interface, so you can't use it with multiple inheritance. That's one reason it was deprecated.
2. Modern Approach: Custom Observer Pattern (Recommended)
Instead of relying on built-in classes, define your own subject-observer contract using interfaces.
Step 1: Define the Observer Interface
@FunctionalInterface public interface Observer<T> { void update(T data); }
Step 2: Implement the Subject
import java.util.ArrayList; import java.util.List; public class WeatherStation { private List<Observer<Float>> observers = new ArrayList<>(); private float temperature; public void addObserver(Observer<Float> observer) { observers.add(observer); } public void removeObserver(Observer<Float> observer) { observers.remove(observer); } public void setTemperature(float temperature) { this.temperature = temperature; notifyObservers(); } private void notifyObservers() { for (Observer<Float> observer : observers) { observer.update(temperature); } } public float getTemperature() { return temperature; } }
Step 3: Use It with Lambda Expressions
public class ModernObserverDemo { public static void main(String[] args) { WeatherStation station = new WeatherStation(); // Add observers using lambdas station.addObserver(temp -> System.out.println("Phone Display: " temp "°C")); station.addObserver(temp -> System.out.println("TV Display: " temp "°C")); station.addObserver(temp -> { if (temp > 28) { System.out.println("Alert: High temperature detected!"); } }); // Change state station.setTemperature(25.0f); station.setTemperature(29.5f); } }
Output:

Phone Display: 25.0°C TV Display: 25.0°C Phone Display: 29.5°C TV Display: 29.5°C Alert: High temperature detected!
This approach is:
- More flexible (uses interfaces, not concrete classes)
- Supports lambda expressions
- Easier to test and extend
- Not tied to deprecated APIs
3. Alternative: Using PropertyChangeListener
(For GUI or Bean-like Objects)
Java also has java.beans.PropertyChangeListener
, which is still not deprecated and useful in certain contexts (like Swing or POJOs with property change events).
import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; public class SmartThermostat { private final PropertyChangeSupport support = new PropertyChangeSupport(this); private int targetTemp; public void addPropertyChangeListener(PropertyChangeListener listener) { support.addPropertyChangeListener(listener); } public void setTargetTemp(int newTemp) { int old = this.targetTemp; this.targetTemp = newTemp; support.firePropertyChange("targetTemp", old, newTemp); } }
Useful when you want to track which property changed and its old/new values.
Summary
Approach | Status | Use Case |
---|---|---|
Observable / Observer
|
❌ Deprecated | Legacy code only |
Custom Observer Interface | ✅ Recommended | General purpose, clean, modern |
PropertyChangeListener |
✅ Available | GUI apps, bean properties |
For new projects, go with a custom observer interface — it's simple, type-safe, and works well with lambdas.
Basically, just:
- Define an
Observer<t></t>
interface - Maintain a list of listeners in your subject
- Notify them on state change
That’s the Observer pattern done right in modern Java.
以上是如何使用Java中的观察者模式?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undress AI Tool
免费脱衣服图片

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Importjava.ioandjava.net.SocketforI/Oandsocketcommunication.2.CreateaSocketobjecttoconnecttotheserverusinghostnameandport.3.UsePrintWritertosenddataviaoutputstreamandBufferedReadertoreadserverresponsesfrominputstream.4.Usetry-with-resourcestoautomati

容器化Java应用:创建Dockerfile,使用基础镜像如eclipse-temurin:17-jre-alpine,复制JAR文件并定义启动命令,通过dockerbuild构建镜像并用dockerrun测试本地运行。2.推送镜像到容器注册表:使用dockertag标记镜像并推送到DockerHub等注册表,需先登录dockerlogin。3.部署到Kubernetes:编写deployment.yaml定义Deployment,设置副本数、容器镜像和资源限制,编写service.yaml创建

VSCode中可通过快捷键快速切换面板与编辑区。要跳转至左侧资源管理器面板,使用Ctrl Shift E(Windows/Linux)或Cmd Shift E(Mac);返回编辑区可用Ctrl `或Esc或Ctrl 1~9。相比鼠标操作,键盘快捷键更高效且不打断编码节奏。其他技巧包括:Ctrl KCtrl E聚焦搜索框,F2重命名文件,Delete删除文件,Enter打开文件,方向键展开/收起文件夹。

runthewindowsupdatetrubloubleshooterviaSettings>更新&安全> is esseShootsoAtomationfixCommonissues.2.ResetWindowSupDateComponentsByStoppingRealatedServices,RenamingTheSoftWaredWaredWaredSoftwaredSistribution andCatroot2Folders,intrestrestartingthertingthertingtherserviceSteStoceTocle

AwhileloopinJavarepeatedlyexecutescodeaslongastheconditionistrue;2.Initializeacontrolvariablebeforetheloop;3.Definetheloopconditionusingabooleanexpression;4.Updatethecontrolvariableinsidethelooptopreventinfinitelooping;5.Useexampleslikeprintingnumber

JavaserializationConvertSanObject'SstateIntoAbyTeSteAmForStorageorTransermission,andDeserializationReconstructstheObjectStheObjectFromThstream.1.toenableserialization,aclassMustimustimplementTheSerializableizableface.2.UseObjectObjectObjectObjectOutputputputputputtreamToserialializeanobectizeanobectementeabectenobexpent,savin

NumPy数组的使用包括:1.创建数组(如从列表、全零、全一、范围创建);2.形状操作(reshape、转置);3.向量化运算(加减乘除、广播、数学函数);4.索引与切片(一维和二维操作);5.统计计算(最大值、最小值、均值、标准差、求和及轴向操作);这些操作高效且无需循环,适合大规模数值计算,最终掌握需多加练习。

ahashmapinjavaiSadattrastureturethatStoreskey-valuepairsforefficeFitedReval,插入和deletion.itusesthekey’shashcode()methodtodeTermInestorageLageLageAgeLageAgeAgeAgeAgeAneStorageAgeAndAllowSavereo(1)timecomplexityforget()
