-
观察者模式 = 主题(Subject) + 观察者(Observer)
观察者__注册__到主题上, 这样在主题数据改变时就会__通知__观察者;
主题对象会管理某些数据;
当主题对象中的数据改变时, 就会通知观察者
主题对象是被观察的一方,观察者是观察的一方,所以是主题对象(被观察)发生变化时通知观察者(观察)
-
观察者模式
定义了对象之间的__一对多__依赖, 这样一来当一个对象改变状态时, 它的所有依赖者都会收到通知并自动更新
-
观察者的实现方式有好几种, 常见的是有一个Subject和一个Observer接口
Observeer中有一个__update()__方法, 当主题中的数据改变时, 会调用关联的Observer的update()方法
-
观察者提供了一种设计方法, 使得主题和观察者之间__松耦合__
-
Java中提供了内置的观察者模式的支持: Observer接口和Observable类, 但是从JDK9之后__被Deprecated了__
-
观察者模式有__两种__做法:
推的方式: 当主题Subject内部有数据更新时, 调用它关联的Observer的update()方法;
示例
public void update(float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; display(); }拉的方式: 当Observer需要update时, 它调用关联的Subject的get()方法
示例
public void update(Observable obs, Object arg) { if (obs instanceof WeatherData) { WeatherData weatherData = (WeatherData) obs; this.temperature = weatherData.getTemperature(); this.humidity = weatherData.getHumidity(); display(); } }可以看到"拉的方式"使用了关联的WeatherData对象的getTemperature和getHumidity方法
一般认为, "推的方式"更合理
-
设计原则:
为交互对象之间的__松耦合__设计而努力
-
Swing中大量应用观察者模式, 例如某个控件绑定了很多事件, 当动作发生时, 会触发这些事件
示例
public class SwingObserverExample { JFrame frame; public static void main(String[] args) { SwingObserverExample example = new SwingObserverExample(); example.go(); } public void go() { frame = new JFrame(); JButton button = new JButton("Should I do it?"); button.addActionListener(new AngelListener()); button.addActionListener(new DevilListener()); frame.getContentPane().add(BorderLayout.CENTER, button); // Set frame properties frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 300); frame.setVisible(true); } class AngelListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("Don't do it, you might regret it!"); } } class DevilListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("Come on, do it!"); } } }
chapter02_观察者模式
最新推荐文章于 2025-11-21 16:00:03 发布
本文深入解析观察者模式,探讨主题与观察者之间的松耦合关系,介绍推与拉两种实现方式,以及Java内置支持。通过具体示例,展示如何在Swing等场景下应用观察者模式,实现对象间高效通讯。
195

被折叠的 条评论
为什么被折叠?



