【JS】观察者模式

来源:互联网 发布:淘宝女包2016新款上市 编辑:程序博客网 时间:2024/05/21 06:40

一个故事。

一个姑娘,lucy,姑娘下载了名叫微信的App。

const log = console.log;function Gril(name){    this.name = name;    this.persionList = [];}

有了微信,得添加一些朋友,才能够成朋友圈。

Gril.prototype.addPersion = function(persion){    this.persionList.push(persion);}

对了,想加好友总得先有人吧。

function Persion(name,relation){    this.name = name;    this.relation = relation;}Persion.prototype.update = function(){}

朋友总有误加的,也需要删除。

Gril.prototype.removePersion = function(persion){    let index = this.persionList.indexOf(persion);    if(index > -1){        this.persionList.splice(index,1);    }}

有了好友,还得能够发送自己动态,好友们能及时知道自己的状态。

Gril.prototype.notify = function(content){    log(`${this.name}: I am ${content}`);    let len = this.persionList.length;    for(let i=0;i<len;i++){        this.persionList[i].update(content);    }}

发生了什么?

  • 1.lucy是谁?
let gril = new Gril('lucy');

  • 2.lucy想加father为好友
let father = new Persion('Jack','parent');//父亲收到lucy的总得做的响应father.update = function(content){    if(Object.is('sad',content)){        log(`${this.name}(${this.relation}): look,plane!!`);    }else if(Object.is('happy',content)){        log(`${this.name}(${this.relation}): >_<!!`);    }}gril.addPersion(father);

  • 3.lucy想加boyfriend为好友(这句话好怪)
let boy = new Persion('bob','boyfriend');boy.update = function(content){    if(Object.is('sad',content)){        log(`${this.name}(${this.relation}): give you a flower.`);    }else if(Object.is('happy',content)){        log(`${this.name}(${this.relation}): love you.`);    }else if(Object.is('happier',content)){        log(`${this.name}(${this.relation}): <_<.`);    }}gril.addPersion(boy);

  • 4.万事俱备,lucy要放大招,发表动态喽。
gril.notify('sad');

lucy: I am sad
Jack(parent): look,plane!!
bob(boyfriend): give you a flower.


  • 5.father调皮,删了他。
    gril.removePersion(father);

  • 6.继续发表动态喽。
gril.notify('happy');

lucy: I am happy
bob(boyfriend): love you.


  • 7.lucy开启虐狗模式
gril.notify('happier');

lucy: I am happier
bob(boyfriend): <_<.


总结

  • a.一个目标对象(lucy)
  • b.多个观察者(father,boyfirend)对同一个目标对象(lucy)感兴趣
  • c.当目标对象状态改变(notify)时,观察者也随之改变(update)