关于“观察者模式”(摘自维基百科,对观察者模式的介绍)
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
It is mainly used to implement distributed event handling systems, in “event driven” software. Most modern languages such as C# have built in “event” constructs which implement the observer pattern components, for easy programming and short code.
The observer pattern is also a key part in the familiar model–view–controller (MVC) architectural pattern. The observer pattern is implemented in numerous programming libraries and systems, including almost all GUI toolkits.
代码示例如下:
/**
* Proxy 实现观察者模式,监听对象数据的变化
*/
// 定义观察者
const observer = new Set();
observer.add((key) => console.log(`执行观察者1:${key} 的值发生了变化`));
observer.add((key) => console.log(`执行观察者2:${key} 的值发生了变化`));
// 定义 observable函数
// 该函数返回一个原始对象的 Proxy 代理,拦截赋值操作,并触发观察者的各个函数。
const observable = obj => new Proxy(obj, {
set(target, key, value, receiver) {
if (target[key] === value) return;
// 执行观察者函数集
observer.forEach(fn => fn(key));
// 赋值并返回
return Reflect.set(target, key, value, receiver);
},
get(target, key) {
console.log(`用户读取了 ${key} 的值`);
return target[key];
}
});
// 测试 观察目标
let person = observable({name: 'Lucy', age: 20});
在谷歌浏览器测试结果:

本文深入介绍了观察者模式,一种软件设计模式,主体对象维护依赖者列表并自动通知状态改变。适用于分布式事件处理和事件驱动软件,如C#等现代语言内置事件构造。观察者模式是MVC架构关键部分,广泛应用于GUI工具包。

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



