interface Mediator{ public function sell($name,$number); } abstract class Human{ protected $mediator=null; abstract public function getThings($number); abstract public function buy($name,$number); public function setMediator($mediator) { $this->mediator = $mediator; } public function getMediator() { return $this->mediator; } } class ConcreteMediator implements Mediator{ private $orchardist=null;//果農 private $boss=null;//化肥老闆 public function sell($name,$number){ if($name == 'fruit'){ $fruit=$this->orchardist->getThings($number); echo '商場從果農給你'.$fruit.'!'."\n"; return $fruit; } if($name == 'fertilizer'){ $fertilizer=$this->boss->getThings($number); echo '商場從化肥老闆那裏給你'.$fertilizer.'!'."\n"; return $fertilizer; } } public function setOrchardist( $orchardist ){ $this -> orchardist = $orchardist; } public function setBoss( $boss ){ $this -> boss = $boss; } } class Orchardist extends Human{ public function __construct($mediator){ $this->mediator=$mediator; } public function getThings($number){ return $number.'水果'; } public function buy($name,$number){ $result=$this->mediator->sell($name,$number); echo '咱們果農獲得了'.$result."\n"; } } class Boss extends Human{ public function __construct($mediator){ $this->mediator=$mediator; } public function getThings($number){ return $number.'化肥'; } public function buy($name,$number){ $result=$this->mediator->sell($name,$number); echo '咱們化肥老闆獲得了'.$result."\n"; } } $mediator=new ConcreteMediator(); $orchardist=new Orchardist($mediator); $boss=new Boss($mediator); $mediator->setOrchardist($orchardist); $mediator->setBoss($boss); $orchardist->buy('fertilizer',200);//果農買200袋化肥 $boss->buy('fruit',50);//化肥老闆買50個水果
中介者模式:顧名思義,就是找個中介,就像房屋中介同樣。中介者模式使原本對象間一對多的模式轉化成一對一的模式,及對象和中介者間的模式,下降了對象之間的耦合度,減小維護成本,是迪米特法則的應用。用兩張網上很形象的圖來講明:
php
圖1:聯繫方式A
圖2:聯繫方式B ui