javascript设计模式之观察者模式(行为模式)

javascript设计模式之观察者模式

js的设计模式分为创建型模式,结构型模式和行为模式

行为模式描述了对象之间的通信行为。

观察者模式又叫发布–订阅模式,是一种常见的行为模式。

下面是示例代码:

// obesever mode
var observer = {
  // add a subscriber
  addSubscribes:function (callback){
    if(typeof callback === 'function'){
      this.subscribes[this.subscribes.length] = callback;
    }
  },

  // remove a subscriber
  removeSubscribes:function (callback){
    for (var i = this.subscribes.length - 1; i >= 0; i--) {
      if(typeof this.subscribes[i] === callback){
        delete this.subscribes[i];
      }
    }
  },

  // publish event
  publish:function (what){
    for (var i = this.subscribes.length - 1; i >= 0; i--) {
      if(typeof this.subscribes[i] === 'function'){
        this.subscribes[i](what);
      }
    }
  },

  // turn an object into a observer
  make:function (o){
    for(var i in this){
      if(this.hasOwnProperty(i)){
        o[i] = this[i];
        o.subscribes = [];
      }
    }
  }
};

var blogger = {
  writeBlogPost:function (){
    var content = 'hello' + new Date();
    this.publish(content);
  }
};

var la_time = {
  newIssue:function (){
    var issue = 'Martians has landed on Earth!';
    this.publish(issue);
  }
};

observer.make(blogger);
observer.make(la_time);

var jack = {
  read:function (what){
    console.log('I have just read' + what);
  }
};

var jill = {
  learn:function (what){
    console.log('I also have read an new issue:' + what);
  }
};

blogger.addSubscribes(jack.read);
la_time.addSubscribes(jill.learn);
blogger.writeBlogPost();
la_time.newIssue();
下面是输出结果:

I have just readhelloTue May 02 2017 14:43:49 GMT+0800 (CST)
VM481517:63 I also have read an new issue:Martians has landed on Earth!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值