Observer 模式定义了一种一对多的依赖关系,当另一个对象(主题)改变状态时,多个对象(观察者)会自动得到通知。它支持解耦的、事件驱动的通信——广泛用于 UI、事件系统和响应式编程。
Observer 模式的作用
OBSERVER → a SUBJECT maintains a list of OBSERVERS and NOTIFIES them on state changes:
→ observers SUBSCRIBE to the subject
→ when the subject changes → it notifies ALL subscribed observers automatically
→ observers react to the notification (update themselves)
→ one-to-many: one subject, many observers; DECOUPLED (subject doesn't know observer details)
示例
{
observers = [];
() { ..(obs); }
() { ..( obs.(data)); }
}
subject.({ : .(, data) });
subject.();
