观察者模式那点事儿

最近在看《JavaScript面向对象编程指南》种的设计模式,主要有三种,工厂模式,装饰器模式和观察者模式,今天分享一下关于观察者模式的演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>订阅发布模式</title>
</head>
<body>
<script>
// 定义发布者对象
var publisher = {
  subscribers: [],

  //添加订阅者
  addSubscriber: function(callback) {
    this.subscribers[this.subscribers.length] = callback
  },

  //删除订阅者
  removeSubscriber: function(callback) {
    for(var i=0; i<this.subscribers.length; i++) {
      if(tis.subscribers[i] === callback) {
        delete(this.subscribers[i])
      }
    }
  },

  //发布事件
  publish: function(what) {
    for(var i=0; i<this.subscribers.length; i++) {
      if(typeof this.subscribers[i] === 'function') {
        this.subscribers[i](what)
      }
    }
  },

  //将对象转变车发布者
  make: function(o) {
    for(var i in this) {
      o[i] = this[i];
      o.subscribers = []
    }
   }
}

// 订阅者,负责当发生某个事件的时候调用publish事件
var blogger = {
  writeBlogPost: function() {
    var context = 'today is' + new Date();
    this.publish(context)
  }
}
var la_times = {
  newIssue: function() {
    var paper = 'Martians have loaded on Earth!';
    this.publish(paper)
  }
}
// 它们都很容易装变为发行商
publisher.make(blogger)
publisher.make(la_times)
// 准备两个简单对象
var jack = {
  read: function(what) {
    console.log('I just read that' + what)
  }
};
var jill = {
  gossip: function(what) {
    console.log('You don\'t hear it from me, but ' + what)
  }
}
// 他们可以订阅blogger对象,只需要提供事件发生时的回调函数
blogger.addSubscriber(jack.read);
blogger.addSubscriber(jill.gossip);
blogger.writeBlogPost()
</script>
</body>
</html>

posted @   星马豪  阅读(82)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示