[php]php设计模式 Mediator (中介者模式)

1 <?php
2 /**
3 * 中介者模式
4 *
5 * 用一个中介对象来封装一系列的对象交互,使各对象不需要显式地相互引用从而使其耦合松散,而且可以独立地改变它们之间的交互
6 */
7 abstractclass Mediator
8 {
9 abstractpublicfunction send($message,$colleague);
10 }
11
12 abstractclass Colleague
13 {
14 private$_mediator=null;
15
16 publicfunction Colleague($mediator)
17 {
18 $this->_mediator =$mediator;
19 }
20
21 publicfunction send($message)
22 {
23 $this->_mediator->send($message,$this);
24 }
25
26 abstractpublicfunction notify($message);
27 }
28
29 class ConcreteMediator extends Mediator
30 {
31 private$_colleague1=null;
32 private$_colleague2=null;
33
34 publicfunction send($message,$colleague)
35 {
36 if($colleague==$this->_colleague1)
37 {
38 $this->_colleague1->notify($message);
39 } else {
40 $this->_colleague2->notify($message);
41 }
42 }
43
44 publicfunction set($colleague1,$colleague2)
45 {
46 $this->_colleague1 =$colleague1;
47 $this->_colleague2 =$colleague2;
48 }
49 }
50
51 class Colleague1 extends Colleague
52 {
53 publicfunction notify($message)
54 {
55 echo"Colleague1 Message is :".$message."<br/>";
56 }
57 }
58
59 class Colleague2 extends Colleague
60 {
61 publicfunction notify($message)
62 {
63 echo"Colleague2 Message is :".$message."<br/>";
64 }
65 }
66
67 //
68 $objMediator=new ConcreteMediator();
69 $objC1=new Colleague1($objMediator);
70 $objC2=new Colleague2($objMediator);
71
72 $objMediator->set($objC1,$objC2);
73
74 $objC1->send("to c2 from c1");
75 $objC2->send("to c1 from c2");

posted on 2011-06-24 22:57  bluefrog  阅读(1074)  评论(0编辑  收藏  举报