Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

观察者模式 #9

Open
SoloJiang opened this issue Jun 18, 2019 · 0 comments
Open

观察者模式 #9

SoloJiang opened this issue Jun 18, 2019 · 0 comments
Labels

Comments

@SoloJiang
Copy link
Owner

观察者模式(Observer):又被称作发布-订阅者模式或消息机制,定义了一种依赖关系,解决了主体对象与观察者之间的功能的耦合。

在观察者模式中,核心是三种方法:订阅, 取消订阅, 发送订阅。即:

const Obsever = (function () {
  let message = {}; //将消息容器作为私有变量,防止被污染
  return {
    regist () {},
    fire () {},
    cancel () {} 
  }
})();

我们通过regist函数订阅注册某种类型的事件执行序列,通过fire函数去分发按序列执行某种类型的事件,通过cancel函数去取消订阅。

接下来,我们分步完成这三个函数:

regist (type, fn) {
  if (message[type] === undefined) {
    message[type] = [fn];
   } else {
     message[type].push(fn); // 若该类事件被注册过,则将函数推入执行序列
   }
  console.log('You han regist ' + type + ' 类型的 ' + fn.name + ' 事件');
}
fire (type, info) {
  if (message[type] === undefined || !(message[type] instanceof Array)) return;
  let len = message[type].length;
  message[type].forEach(fn => {
    fn(info);
  });
}
cancel (type, fn) { 
      if (message[type] !== undefined && message[type] instanceof Array) {
        let len = message[type].length;
        message[type].forEach((item, index) => {
          if (item === fn) { // 为了完成对象之间的解耦,能取消注册的函数必须就是注册的函数
            message[type].splice(index, 1);
            console.log('You had remove ' + fn.name);
          }
        })
      }
    } 

上面的代码浅显易懂,接下来贴一下测试代码,看看我们是不是完成了整个流程控制:

const obj = {
  say () {
    console.log('Hi~');
  }
}
Obsever.regist('onsay', obj.say);

Obsever.fire('onsay');

Obsever.cancel('onsay', obj.say);


以上就是最基本的观察者模式,也是书上所提到的,那么接下来的文章将会对此进行扩展,并且谈谈现在流行库的设计方法。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant