本篇内容主要讲解“js中介者模式怎么实现”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“js中介者模式怎么实现”吧!
概念
1、通过一个中介对象,所有其他相关对象都通过中介对象通信,而不是相互引用。
2、当一个对象发生变化时,只需通知中介对象。通过中介模式,可以解除对象与对象之间的耦合关系。
实例
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <p>1 0 30</p> <div id="results"></div> <script> //Mediator //这里用了构造器模式 function Player(name) { this.name = name; this.point = 0; } Player.prototype.play = function() { this.point += 1; mediator.played(); } var scoreboard = { ele : document.getElementById("results"), update : function(score) { var i, msg = ""; for(i in score) { if(score.hasOwnProperty(i)) { msg += "<p><strong>" + i + "</strong>"; msg += score[i]; msg += "</p>"; } } this.ele.innerHTML = msg; } }; var mediator = { players : {}, setup : function() { var player = this.players; player.home = new Player("Home"); player.guest = new Player("Guest"); }, played : function() { var player = this.players; score = { Home : player.home.point, Guest : player.guest.point }; scoreboard.update(score); }, keypress : function(e) { e = e || window.event; //事件监听 if(e.which === 49) { mediator.players.home.play(); } if(e.which === 48) { mediator.players.guest.play(); } } }; mediator.setup(); window.onkeypress = mediator.keypress; setTimeout(function(){ window.onkeypress = null; console.log("game over!"); }, 30000); </script> </body> </html>
到此,相信大家对“js中介者模式怎么实现”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。