1. 用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式的相互引用,从而使其耦合松散,而且可以独立地改变他们的交互<br />这个就真的式中介了,你租房,他出租,中介在两边调节,<br />代理类只是返回一个类,用于代理控制,而不是交互<br />中介类处理两个交互类的关系,互相调用需要交互的对象的方法,而对象只需要调用中介提供的接口就可以<br />实现了用户之间的耦合,使得用户之间不用维护关系,都交给中介类,但是不适宜太多用户,不然,中介类会太过臃肿

    image.png

    1. <?php
    2. //抽象中介类
    3. abstract class Mediator
    4. {
    5. abstract public function Send($message, $colleague);
    6. }
    7. //中介实现类
    8. class ConcreteMediator extends Mediator
    9. {
    10. //需要联系操作的类
    11. public $colleague1;
    12. public $colleague2;
    13. //处理的方法,信息和当前的操作类
    14. public function Send($message, $colleague)
    15. {
    16. if ($colleague == $this->colleague1) {
    17. //执行对应类的处理方法
    18. $this->colleague2->Notify($message);
    19. } else {
    20. $this->colleague1->Notify($message);
    21. }
    22. }
    23. }
    24. //联系抽象类
    25. abstract class Colleague
    26. {
    27. protected $mediator;
    28. protected $name;
    29. public function __construct($mediator, $name)
    30. {
    31. $this->mediator = $mediator;
    32. $this->name = $name;
    33. }
    34. }
    35. //联系类A
    36. class ConcreteColleagueA extends Colleague
    37. {
    38. //发送消息
    39. public function Send(string $message)
    40. {
    41. $this->mediator->Send($this->name . "说:" . $message, $this);
    42. }
    43. //接受消息
    44. public function Notify(string $message)
    45. {
    46. echo $this->name . "得到信息:" . $message, PHP_EOL;
    47. }
    48. }
    49. //联系类B
    50. class ConcreteColleagueB extends Colleague
    51. {
    52. public function Send(string $message)
    53. {
    54. $this->mediator->Send($this->name . "说:" . $message, $this);
    55. }
    56. public function Notify(string $message)
    57. {
    58. echo $this->name . "得到信息:" . $message, PHP_EOL;
    59. }
    60. }
    61. //实例化中介类
    62. $ConcreteMediator = new ConcreteMediator();
    63. //联系类
    64. $ConcreteColleagueA = new ConcreteColleagueA($ConcreteMediator, '天天');
    65. $ConcreteColleagueB = new ConcreteColleagueB($ConcreteMediator, '小明');
    66. //中介类对应关系
    67. $ConcreteMediator->colleague1=$ConcreteColleagueA;
    68. $ConcreteMediator->colleague2=$ConcreteColleagueB;
    69. //联系
    70. $ConcreteColleagueA->Send('你在哪呢,还不回来');
    71. $ConcreteColleagueA->Send('再不回来,没肉吃了');
    72. $ConcreteColleagueB->Send('等我,马上');