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

1 <? php
2 /* *
3 * 中介者模式
4 *
5 * 用一个中介对象来封装一系列的对象交互,使各对象不需要显式地相互引用从而使其耦合松散,而且可以独立地改变它们之间的交互
6 */
7 abstract class Mediator
8 {
9 abstract public function send( $message , $colleague );
10 }
11
12 abstract class Colleague
13 {
14 private $_mediator = null ;
15
16 public function Colleague( $mediator )
17 {
18 $this -> _mediator = $mediator ;
19 }
20
21 public function send( $message )
22 {
23 $this -> _mediator -> send( $message , $this );
24 }
25
26 abstract public function notify( $message );
27 }
28
29 class ConcreteMediator extends Mediator
30 {
31 private $_colleague1 = null ;
32 private $_colleague2 = null ;
33
34 public function 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 public function set( $colleague1 , $colleague2 )
45 {
46 $this -> _colleague1 = $colleague1 ;
47 $this -> _colleague2 = $colleague2 ;
48 }
49 }
50
51 class Colleague1 extends Colleague
52 {
53 public function notify( $message )
54 {
55 echo " Colleague1 Message is : " . $message . " <br/> " ;
56 }
57 }
58
59 class Colleague2 extends Colleague
60 {
61 public function 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 " );

你可能感兴趣的:(media)