对观察者模式的理解,参考来自之前文章提到的来自DZone的Cheat Sheet。

Observer/观察者模式:

UML类图:

    TODO

Purpose/模式定义:

    Lets one or more objects be notified of state changes in other objects within the system.

    当系统中某些对象的状态发生改变时,能够向其他的一个或多个对象发出通知。

Use When/Scenario/应用场景:

  • State changes in one or more objects should trigger behavior in other objects;
  • Broadcasting capabilities are required;
  • An understanding exists that objects will be blind to the expense of notification.
  • 一些对象的状态更改需要出发其他对象的动作;
  • 需要实现广播功能;
  • 对象内部的功能处理对于通知的花费是透明的(不知如何翻译:()。

 Example/应用实例:

    This pattern can be found in almost every GUI environment. When buttons,text, and other fields are placed in applications the application typically registers as a listener for those controls. When a user triggers and event, such as clicking a button, the control iterates through its registered observers and sends a notification to each.

    几乎所有的图形用户界面环境中我们都能看到这种模式(观察者模式)。在应用程序中,我们放置按钮、文本框、以及其他元素后,程序会为这些控件注册一个监听器。每当用户触发一个事件,例如点击按钮,这个控件就是遍历已经注册监听它的所有观察者并向它们逐一发送通知。