觀察者模式 又稱 訂閱發佈模式dom
QQ Email 客戶端訂閱消息 從報社發佈消息,而後客戶d端接收。this
代碼以下:spa
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"));