码迷,mamicode.com
首页 > 其他好文 > 详细

观察者模式那点事儿

时间:2018-06-15 16:13:29      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:gossip   Oday   char   工厂   观察者   read   typeof   TE   doctype   

最近在看《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>

观察者模式那点事儿

标签:gossip   Oday   char   工厂   观察者   read   typeof   TE   doctype   

原文地址:https://www.cnblogs.com/shenwh/p/9186607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!