简单实现 class Event { constructor() {this.lists = new Map(); }
总是把这两个看成同一个模式,但其实是不太一样的,此刻重温一下。
不雅察看者模式不雅察看者直接订阅方针,当方针触发事件时,通知不雅察看者进行更新
简单实现
class Observer { constructor(name) { this.name = name; } update() { console.log(`${this.name} update`) } } class subject { constructor() { this.subs = []; } add(observer) { this.subs.push(observer); } notify() { this.subs.forEach(item => { item.update(); }); } } const sub = new subject(); const ob1 = new Observer('ob1'); const ob2 = new Observer('ob2'); // 不雅察看者订阅方针 sub.add(ob1); sub.add(ob2); // 方针触发事件 sub.notify(); 颁布订阅模式颁布订阅模式通过一个调理中心进行措置惩罚惩罚,使得订阅者和颁布者分分开来,互不滋扰。
简单实现
class Event { constructor() { this.lists = new Map(); } on(type, fn) { if (!this.lists.get(type)) { this.lists.set(type, []); } this.lists.get(type).push(fn); } emit(type, ...args) { const arr = this.lists.get(type); arr && arr.forEach(fn => { fn.apply(null, args); }); } } const ev = new Event(); // 订阅 ev.on('msg', (msg) => console.log(msg)); // 颁布 ev.emit('msg', '颁布'); 差别点其实这两个模式可以说是同一种设计模式的差别实现。
不雅察看者模式是不雅察看者和方针直接进行交互,有耦合性,,而颁布订阅模式则是通过一个调理中心进行措置惩罚惩罚,订阅者和颁布者互不滋扰,进行了解耦。
js 设计模式:不雅察看者和颁布订阅模式
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/32860.html