当前位置: 移动技术网 > IT编程>开发语言>PHP > php中的设计模式之--中介模式

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

2018年02月17日  | 移动技术网IT编程  | 我要评论
系统就是一个中介模式 ,
		朋友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");

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网