php中的設計模式之--中介模式
朋友1
我<-->QQ <---->朋友2
<---->朋友13
*/
// 抽象中介,QQ聊天
interface ChatMediator { // 中介者角色
public function sendMessage($msg,$user);
public function addQQUser($user);
}
// 抽象用戶
abstract class User {
protected $mediator;
protected $name;
public function __construct($med, $name){
$this->mediator = $med;
$this->name = $name;
}
public abstract function send($msg);
public abstract function receive($msg);
}
class QQchat implements ChatMediator {
// 用戶列表
private $users;
public function __construct(){
$this->users = null ;
}
// 添加用戶
public function addQQUser($user){
$this->users[] = $user;
}
// 發送具體的QQ信息通過QQ發送
public function sendMessage($msg, $user) {
foreach($this->users as $k =>$v){
// 自己發送的自己不能接受
if($v != $user){
// 調用好友的接口
$v->receive($msg);
}
}
}
}
// 具體對象角色
class QQUser extends User {
public function send($msg){
$this->mediator->sendMessage($msg, $this);
}
// 接受
public function receive($msg) {
echo $this->name.' receive '.$msg.'
' ;
}
}
// client
// 中介為QQ
$QQchat = new QQchat();
$oMe = new QQUser($QQchat, "張三");
$oFriend1 = new QQUser($QQchat, "李四");
$oFriend2 = new QQUser($QQchat, "王偉");
$oFriend3 = new QQUser($QQchat, "大哥");
// 添加好友
$QQchat->addQQUser($oMe);
$QQchat->addQQUser($oFriend1);
$QQchat->addQQUser($oFriend2);
$QQchat->addQQUser($oFriend3);
$oMe->send("Hi All");