欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

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

程序员文章站 2022-04-15 18:21:01
...
朋友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");