觀察者模式詳解
阿新 • • 發佈:2018-12-18
觀察 理解 訂閱 分享圖片 log 事件 img con 詳解
觀察者模式的理解:
觀察者模式就是、 某個人--->觀察某件事件---》事情發生變化---》通知這個人---》去做某件事情
以下案例是騰訊公司發布訂閱的小案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> </body> </html> <script> function tengxun(){this.訂閱者們 = []; this.發送 = function(){ var mes = this.message(); for(var i in this.訂閱者們){ this.訂閱者們[i].訂閱(mes) } } this.訂閱頻道 = function(qq){ this.訂閱者們.push(qq); } this.message = function(){ return "來自騰訊的消息"; } } function QQ(qq){this.qq = qq; this.訂閱 = function(mes){ console.log(this.qq+"您收到"+new Date()+mes) } } var gongsi = new tengxun(); gongsi.訂閱頻道(new QQ("1234567")) gongsi.訂閱頻道(new QQ("abcdfr")) gongsi.訂閱頻道(new QQ("9087654")) gongsi.訂閱頻道(new QQ("4564564")) gongsi.發送(); </script>
結果:
觀察者模式詳解