设计模式:发布订阅模式实现的是一种多对多的关系,在发布者与订阅者之间需要有一个中介者,发布者发布事件名和参数到中间者,中间者向事件集中的订阅者发送参数。而观察者

81 阅读1分钟

观察者模式:

就是在class构造函数里 设置一个状态 通过 构造函数里面写好的方法直接对数据进行操作。

class obj {
  state = ["构造函数"];
  set(arr) {
    this.state = arr;
  }
  get() {
    return this.state;
  }
}
let Objs = new obj();
export default Objs 

// 页面使用
Objs.set(变量) 赋值
Objs.get()    获取参数

发布订阅模式:

就是在class构造函数中 设置一个对象,可以进行绑定事件 执行事件 取消绑定

class objsever {
  constructor() {
    this._data = {};
    this._obj = { a: "aaaaaaaa" };
  }

  on(type, fn) {
    if (!this._data[type]) {
      this._data[type] = [fn];
    } else {
      this._data[type] = [...this._data[type], fn];
    }
    fn({ msg: "订阅成功" });
  }

  emit(type, fn, data) {
    this._data[type].forEach((ele) => {
      if (ele === fn) {
        const obj = {
          type,
          clientX: 0,
          clientY: 0,
        };
        ele({ msg: "发布成功", ...obj, ...data });
      }
    });
  }

  off(type, fn) {
    this._data[type] = this._data[type].filter((ele) => ele !== fn);
    fn({ msg: "取消成功" });
  }
}

const ObjServer = new objsever();
export default ObjServer;


// 页面使用 
import React, { useEffect } from "react";
import ObjServer from "./../Obsever";
function ms_one() {
  const fn = (e) => console.log(e);
  useEffect(() => {
    ObjServer.on("click", fn); // 绑定一个事件 订阅
    ObjServer.emit("click", fn, {
      name: "123",
      pass: "222",
      actions: "发布订阅",
    }); // 执行绑定的事件 发布
    return () => {
      ObjServer.off("click", fn); // 取消绑定的事件 取消
    };
  }, []);
  return <div>我是一个组件</div>;
}

export default ms_one;