论坛首页 Java企业应用论坛

设计模式学习笔记JAVA 01(观察者模式)—2014_3_21

浏览 13868 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2014-03-21  

*******************************************

为什么选择设计模式

 

*******************************************

 

看了 head first design pattern,浏览了一下 《大话设计模式》,感觉设计模式的学习会比较有趣,因为能利用现实生活中的故事来理解设计模式。

 

学习笔记的主要参考书是 head first design pattern,因为完整的只有英文版,所以笔记中会 copy 很多英文原句。

 

 

*****************************

气象发布 引发的模式

 

要做什么?

*****************************

 

有三个玩家,如下



 

The three players in the system are the weather station (the physical device that
acquires the actual weather data), the WeatherData object (that tracks the data coming
from the Weather Station and updates the displays), and the display that shows users
the current weather conditions.

 

简而言之,气象站更新天气预报后,张三能够通过手机看到更新后的天气预报。

中间项 WeatherData 负责连接。

 

然后,就有任务了

Our job, if we choose to accept it, is to create an app that
uses the WeatherData object to update three displays for
current conditions, weather stats, and a forecast.



 

零零豆:我要10万精兵,再加10吨战备茅台。

 

不行,给你的只有



 

we have to figure out what we need to do. So, what do we know so far?

 

  • The WeatherData class has getter methods for three measurement values: temperature, humidity and barometric pressure.
  • The measurementsChanged() method is called any time new weather measurement data is available
  • We need to implement three display elements that use the weather data: a current conditions display, a statistics display and a forecast display. These displays must be updated each time WeatherData has new measurements.
  • The system must be expandable—other developers can create new custom display elements and users can add or remove as many display elements as they want to the application. Currently, we know about only the initial three display types

 

 

  • 大小: 47 KB
  • 大小: 39 KB
  • 大小: 33.4 KB
   发表时间:2014-03-21  

************************************

第一次 尝试

 

************************************

 

第一这样写(是有问题的)

public class WeatherData {
// instance variable declarations
public void measurementsChanged() {
float temp = getTemperature();
float humidity = getHumidity();
float pressure = getPressure();
currentConditionsDisplay.update(temp, humidity, pressure);
statisticsDisplay.update(temp, humidity, pressure);
forecastDisplay.update(temp, humidity, pressure);
}
}

 

对 *Display.update 函数来说,

By coding to concrete implementations we have no way to add or remove other display elements without making changes to the program.

 

被困住了。



 

 

  • 大小: 21.1 KB
0 请登录后投票
   发表时间:2014-03-21  

*********************************************

白马王子 来了

 

*********************************************



 
 认识一下,

  • A newspaper publisher goes into business and begins publishing newspapers.
  • You subscribe to a particular publisher, and every time there’s a new edition it gets delivered to you. As long as you remain a subscriber, you get new newspapers.
  • You unsubscribe when you don’t want papers anymore, and they stop being delivered.
  • While the publisher remains in business, people, hotels, airlines and other businesses constantly subscribe and unsubscribe to the newspaper.

 

 

观察者模式现身了,

 


 

The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are
notified and updated automatically.

 

 

  • 大小: 40.1 KB
  • 大小: 42.3 KB
0 请登录后投票
   发表时间:2014-03-21  

************************************

观察者模式 类图

 

************************************


 

A concrete subject always implements the Subject interface.

In addition to the register and remove methods, the concrete subject implements a notifyObservers() method that is used to update all the current observers whenever state changes
 

Each subject can have many observers.



 

  • 大小: 39.1 KB
  • 大小: 44.5 KB
0 请登录后投票
   发表时间:2014-03-22  

***************************************

The power of Loose Coupling

 

某国畸形现象的根源

***************************************



 When two objects are loosely coupled, they can interact, but have very little knowledge of each other.


The Observer Pattern provides an object design where subjects and observers are loosely coupled.

 

Why?

 

  • The only thing the subject knows about an observer is that it implements a certain interface.
  • We can add new observers at any time.
  • We never need to modify the subject to add new types of observers.
  • We can reuse subjects or observers independently of each other.
  • Changes to either the subject or an observer will not affect the other.

 

Loosely coupled designs allow us to build flexible OO systems that can handle change because they minimize the interdependency between objects.

 

说得真不错,比部长还高一个水平。

 

如果,能够做到 loosely coupling,那么下面这种事情是不会发生的。



 

 

  • 大小: 39.6 KB
  • 大小: 85.6 KB
0 请登录后投票
   发表时间:2014-03-22  

************************************

让气象站 也成为 观察者 模式

 

************************************


 

So, let’s get started with the interfaces:

 

 

public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
}

 notifyObservers() method is called to notify all observers when the Subject’s state has changed.

 

 

public interface Observer {
public void update(float temp, float humidity, float pressure);
}

 The Observer interface is implemented by all observers, so they all have to implement the update() method.

 

public interface DisplayElement {
public void display();
}

 The DisplayElement interface just includes one method, display(), that we will call when the display element needs to be displayed.


有了接口,就可以具体实现了,



 

public class WeatherData implements Subject {
private ArrayList observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherData() {
observers = new ArrayList();
}
public void registerObserver(Observer o) {
observers.add(o);
}
public void removeObserver(Observer o) {
int i = observers.indexOf(o);
if (i >= 0) {
observers.remove(i);
}
}
public void notifyObservers() {
for (int i = 0; i < observers.size(); i++) {
Observer observer = (Observer)observers.get(i);
observer.update(temperature, humidity, pressure);
}
}
public void measurementsChanged() {
notifyObservers();
}
public void setMeasurements(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
measurementsChanged();
}

}

 

Now that we’ve got our WeatherData class straightened out, it’s time to build the Display Elements.

 



 

public class CurrentConditionsDisplay implements Observer, DisplayElement {
private float temperature;
private float humidity;
private Subject weatherData;
public CurrentConditionsDisplay(Subject weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
public void update(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
display();
}
public void display() {
System.out.println(“Current conditions: “ + temperature
+ “F degrees and “ + humidity + “% humidity”);
}
}

 
 

  • 大小: 32.9 KB
  • 大小: 41.9 KB
  • 大小: 31.6 KB
0 请登录后投票
   发表时间:2014-03-22  

**************************************

执行 代码

 

***************************************

 

源代码 从 http://www.headfirstlabs.com/books/hfdp/ 可以下载,

 

源代码是有 package 的,为了方便执行,我都去掉了。

 



 

  • 大小: 51.4 KB
0 请登录后投票
   发表时间:2014-03-23  

从 观察者 模式 到 气象站

 

从网上粘贴过来的,



 



 

  • 大小: 4.6 KB
  • 大小: 7.3 KB
0 请登录后投票
   发表时间:2014-03-23  

*************************************

观察者 模式 相关 应用1

 

**************************************

观察者模式应用场景实例

http://blog.csdn.net/swengineer/article/details/6268244

 

关键信息摘录,

本文只是以哈票网举例,示例中并未涉及哈票网任何业务代码,全部原创,如有雷同,纯属巧合。

 

 

 * 观察者模式典型实现方式:

 * 1、定义2个接口:观察者(通知)接口、被观察者(主题)接口

 * 2、定义2个类,观察者对象实现观察者接口、主题类实现被观者接口

 * 3、主题类注册自己需要通知的观察者

 * 4、主题类某个业务逻辑发生时通知观察者对象,每个观察者执行自己的业务逻辑。

 



 

 

类对象的定义 和 实现 代码 就不写复制过来了,感兴趣可以看 链接的 原文。

 

  • 大小: 45.3 KB
0 请登录后投票
   发表时间:2014-03-23  

******************************

观察者 模式 应用 2

 

*******************************

研磨设计模式 之 观察者模式

http://sishuok.com/forum/posts/list/5281.html

 

感觉这篇文章 更加 细致,如果排版 好一些的话,就更完美了。

 

这篇文章的最大特点在于 动态,模式 又分为 推模式 和 拉模式。

 



 



 

 

观察者模式的本质:触发联动

       当修改目标对象的状态的时候,就会触发相应的通知,然后会循环调用所有注册的观察者对象的相应方法,其实就相当于联动调用这些观察者的方法。

       而且这个联动还是动态的,可以通过注册和取消注册来控制观察者,因而可以在程序运行期间,通过动态的控制观察者,来变相的实现添加和删除某些功能处理,这些功能就是观察者在update的时候执行的功能。

同时目标对象和观察者对象的解耦,又保证了无论观察者发生怎样的变化,目标对象总是能够正确地联动过来。

       理解这个本质对我们非常有用,对于我们识别和使用观察者模式有非常重要的意义,尤其是在变形使用的时候,万变不离其宗。

 

  • 大小: 121.2 KB
  • 大小: 516.8 KB
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics