JS实现观察者模式
观察者模式 又称 订阅发布模式
QQ Email 客户端订阅消息 从报社发布消息,然后客户d端接收。
代码如下:
1 //观察者模式 又称订阅发布模式 2 function Newspaper() { 3 var list = new Set(); 4 //订阅 5 this.subscribe = function(c) { 6 list.add(c); 7 } 8 //取消订阅 9 this.unsubscribe = function(c) { 10 list.remove(); 11 } 12 //发布新闻 13 this.publish = function(msg) { 14 for(var i of list.keys()) { 15 i.notice(msg); 16 } 17 } 18 //每4s产生一条新闻 19 this.start = function() { 20 setInterval(function() { 21 this.publish(Math.random()); 22 }.bind(this), 4000); 23 } 24 } 25 26 function Client() { 27 this.notice = function(msg) { 28 console.log(this.type + "内容:" + msg); 29 } 30 } 31 var QQ = function() { 32 this.type = "QQ"; 33 }; 34 QQ.prototype = new Client(); 35 var Email = function() { 36 this.type = "Email"; 37 }; 38 Email.prototype = new Client(); 39 40 var theme = new Newspaper(); 41 theme.start(); 42 theme.subscribe(new QQ("aaa")); 43 theme.subscribe(new Email("aaa@qq.com"));
用代码书写精彩人生