Home  >  Article  >  php教程  >  php中的设计模式之--中介模式

php中的设计模式之--中介模式

WBOY
WBOYOriginal
2016-06-21 08:47:111089browse

朋友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");



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn