★中介者模式★

所有元素包括类都是统一由个类进行控制、生成、维护、改变状态的,这个类就是中介者

我们看下图没有使用中介者的情况

 

 

我们称上图的状态为“互为信息源”,相互之间都能进行通信,这样造成的后果就是增加了代码的耦合性,并且不易于维护

我们可以使用一个中介者进行左右逢源,所有的其他类都是通过中介者来进行互相通信的

 

 

 

比如我们进行了一次考试,考试成绩决定着你的水平,角色分别是小明,小红,小刚。

 1   <script>
 2     // 测试类,是中介者类,作用就是承接成绩和状态,然后返回已有的消息
 3 function Test(name) {
 4     this.name = name;
 5     this.score = new Score(this.name);
 6     this.state = new State(this.score.result);
 7 }
 8 Test.prototype.cnnouncedResult = function() {
 9     console.log(this.name + "的考试成绩是" + this.score.result + "分,水平是" + this.state.result)
10 }
11 
12 // 成绩类,返回的是对应的成绩信息
13 function Score(name) {
14     switch (name) {
15         case "小明":
16             this.result = 60;
17             break;
18         case "小红":
19             this.result = 90;
20             break;
21         case "小刚":
22             this.result = 80;
23             break;
24     }
25 }
26 function State(score) {
27     // 当前的考试结果返回对应的状态,如果是60分则返回及格,80分是良好,90分以上是优秀
28     if (score >= 60 && score < 80) {
29         this.result = "及格"
30     } else if (score >= 80 && score < 90) {
31         this.result = "良好"
32     } else if (score >= 90) {
33         this.result = "优秀"
34     } else {
35         this.result = "不及格"
36     }
37 }
38 var xiaoming = new Test("小明")
39 var xiaohong = new Test("小红")
40 var xiaogang = new Test("小刚")
41 xiaoming.cnnouncedResult()
42 xiaohong.cnnouncedResult()
43 xiaogang.cnnouncedResult()
44     </script>

posted @ 2021-09-26 22:04  keyeking  阅读(31)  评论(0编辑  收藏  举报