js设计模式(观察者模式,订阅发布模式)

116 阅读1分钟

观察者模式

/**
 * 观察者模式
 * 可以理解为监控,当被观察者的状态发生变化时,触发观察者的技能
 * 场景:教室
 * 观察者:班主任,校长->监控一个对象的状态,一旦状态发生,马上触发技能,需要有自己的属性和技能
 * 被观察者:学生->需要有自己的属性,状态和队列(都有谁观察自己)
 */

// 观察者
class Observer {
  constructor(name, fn = () => {}) {
    this.name = name;
    this.fn = fn;
  }
}

// 被观察者
class Subject {
  constructor(state) {
    this.state = state;
    this.observerList = [];
  }

  // 改变状态
  changeState(value) {
    this.state = value;
    this.observerList.forEach((item) => item.fn(this.state));
  }

  // 添加观察者
  addObserver(observer) {
    this.observerList.push(observer);
  }

  // 删除观察者
  deleteObserver(observer) {
    this.observerList = this.observerList.filter(item !== observer);
  }
}

// =========================
// 创建观察者
const xz = new Observer("校长", (state) => {
  console.log(`因为-${state}-把班主任叫来`);
});
const bzr = new Observer("班主任", (state) => {
  console.log(`因为-${state}-把你家长叫来`);
});

// 创建被观察者
const xm = new Subject("学习");
xm.addObserver(xz);
xm.addObserver(bzr);
xm.changeState("睡觉"); // 触发观察者行为

发布订阅模式

/**
 * 发布-订阅模式
 * 场景: 云端
 * 当有一个人往云端更新或者发布一个文件时,通知其他关注的用户(短信或邮件等)
 */

class Observer {
  constructor() {
    this.message = {};
  }
  // 添加消息
  on(type, fn) {
    if (!this.message[type]) {
      this.message[type] = [];
    }
    this.message[type].push(fn);
  }

  /**
   * 删除消息
   * @param {*} type 消息类型
   * @param {*} fn 事件处理函数
   */
  off(type, fn) {
    // 当fn不存在时删除该消息类型,否则删除该消息类型对应的事件处理函数
    if (!fn) {
      delete this.message[type];
    } else {
      this.message[type] = this.message[type].filter((item) => item !== fn);
    }
  }

  //触发消息
  trigger(type) {
    if (!this.message[type]) return;
    this.message[type].forEach((item) => item());
  }
}

// ============================

const person = new Observer();

person.on("a", handleA);
person.on("a", handleB);
person.on("c", handleC);

person.off("a", handleA);

person.trigger("a");

function handleA() {
  console.log("发短信通知");
}
function handleB() {
  console.log("发邮件通知");
}
function handleC() {
  console.log("其他方式通知");
}