中介者模式(Mediator Pattern): 用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。中介者模式又称为调停者模式,它是一种对象行为型模式。
<?php
//中介者模式
header("Content-type:text/html;Charset=utf-8");
//抽象宠物类
abstract class Pet{
protected $message; //狗的信息
protected $store; //为家教服务的中介机构
function __construct($message,Store $store){
$this->message = $message;
$this->store = $store;
}
//获取个人信息
function getMessage(){
return $this->message;
}
//找学生
/**
* @return mixed
*/
abstract function findDog();
}
//具体同事类,大学生家教
class Big extends Pet{
//狗类型 大狗
public $type = "big";
function __construct($message,Store $store){
parent::__construct($message,$store);
}
//找小狗,让宠物店找
function findDog(){
$this->store->searchDog($this);
}
}
//具体同事类,高中生家教
class Middle extends Pet{
//狗类型 中型狗
public $type = "middle";
function __construct($message,Store $store){
parent::__construct($message,$store);
}
//找小狗,让宠物店找
function findDog(){
$this->store->searchDog($this);
}
}
//具体同事类,初中生家教
class Small extends Pet{
//狗类型 小型狗
public $type = "small";
function __construct($message,Store $store){
parent::__construct($message,$store);
}
//找小狗,让宠物店找
function findDog(){
$this->store->searchDog($this);
}
}
//具体的宠物店
class Store{
//定义其服务的所有家教,不在范围内的不服务
private $serveObject = array("big","middle","small");
//匹配学生
public function searchDog(Pet $tutor){
if(!in_array($tutor->type,$this->serveObject)){
echo "此类型不在本店内";
}
foreach ($this->serveObject as $key => $value){
if( $tutor->type = $value){
$message = $tutor->getMessage();
echo "狗信息为".var_dump($message)."<br/>将为其匹配合适的主人";
break;
}
}
}
}
//测试
$big = new Big(array("name"=>"大狗","type"=>'hsq'),new Store());
$big->findDog();












网友评论