php中的設計模式之--中介模式_PHP教程

來源:互聯網
上載者:User

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

http://www.bkjia.com/PHPjc/953321.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/953321.htmlTechArticlephp中的設計模式之--中介模式 朋友1 我 QQ 朋友2 朋友13*/// 抽象中介,QQ聊天 interface ChatMediator { // 中介者角色 public function sendMessage($msg,$user)...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.