Observer 观察者
Intent
Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing.
又被称为发布-订阅 Publish/Subscribe 模式,它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态变化时,会通知所有的观察者对象,使他们能够自动更新自己

Problem
假设有两种类型的对象: Customer and Store.
顾客可以每天来商店看看产品是否到货。但如果商品尚未到货时,绝大多数来到商店的顾客都会空手而归。

另一方面,每次新产品到货时,商店可以向所有顾客发送邮件 (可能会被视为垃圾邮件)。这样,部分顾客就无需反复前往商店了,但也可能会惹恼对新产品没有兴趣的其他顾客。
我们似乎遇到了一个矛盾: 要么让顾客浪费时间检查产品是否到货,要么让商店浪费资源去通知没有需求的顾客。
Solution
The object that has some interesting state is often called subject, but since it’s also going to notify other objects about the changes to its state, we’ll call it publisher. All other objects that want to track changes to the publisher’s state are called subscribers.
The Observer pattern suggests that you add a subscription mechanism to the publisher class so individual objects can subscribe to or unsubscribe from a stream of events coming from that publisher. 观察者模式建议你为发布者类添加订阅机制,让每个对象都能订阅或取消订阅发布者事件流。
- an array field for storing a list of references to subscriber objects. 一个用于存储订阅者对象引用的列表成员变量
- several public methods which allow adding subscribers to and removing them from that list. 几个用于添加或删除该列表中订阅者的公有方法

Now, whenever an important event happens to the publisher, it goes over its subscribers and calls the specific notification method on their objects. 无论何时发生了重要的发布者事件, 它都要遍历订阅者并调用其对象的特定通知方法。
Real apps might have dozens of different subscriber classes that are interested in tracking events of the same publisher class. You wouldn’t want to couple the publisher to all of those classes. Besides, you might not even know about some of them beforehand if your publisher class is supposed to be used by other people. 实际应用中可能会有十几个不同的订阅者类跟踪着同一个发布者类的事件,你不会希望发布者与所有这些类相耦合的。此外如果他人会使用发布者类,那么你甚至可能会对其中的一些类一无所知。
因此,所有订阅者都必须实现同样的接口,发布者仅通过该接口与订阅者交互。接口中必须声明通知方法及其参数, 这样发布者在发出通知时还能传递一些上下文数据。

如果你的应用中有多个不同类型的发布者,且希望订阅者可兼容所有发布者,那么你甚至可以进一步让所有订阅者遵循同样的接口。该接口仅需描述几个订阅方法即可。这样订阅者就能在不与具体发布者类耦合的情况下通过接口观察发布者的状态。
Real-World Analogy

如果你订阅了一份杂志或报纸,那就不需要再去报摊查询新出版的刊物了。publisher 会在刊物出版后直接将最新一期寄送至你的邮箱中。
publisher 负责维护subscribers列表,了解subscribers对哪些刊物感兴趣。当subscribers