码迷,mamicode.com
首页 > Web开发 > 详细

设计模式之中介者模式(php实现)

时间:2018-06-10 19:31:47      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:ati   car   设计   发送   reg   github   static   use   oom   

github地址:https://github.com/ZQCard/design_pattern
/**
 * 中介者模式(Mediator Pattern)是用来降低多个对象和类之间的通信复杂性。
 * 用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
 * 我们通过聊天室实例来演示中介者模式。实例中,多个用户可以向聊天室发送消息,聊天室向所有的用户显示消息。我们将创建两个类 ChatRoom 和 User。User 对象使用 ChatRoom 方法来分享他们的消息。
 */

(1)ChatRoom.class.php(聊天室类)

<?php

namespace Mediator;

class ChatRoom
{
    public static function showMessage(User $user, $message)
    {
        print_r($user->getName()." says: ".$message);
        echo ‘<br/>‘;
    }
}

(2)User.class.php (用户类)

<?php

namespace Mediator;

class User
{
    private $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function sendMessage($message)
    {
        ChatRoom::showMessage($this, $message);
    }
}

(3)mediator.php(客户端)

<?php

spl_autoload_register(function ($className){
    $className = str_replace(‘\\‘,‘/‘,$className);
    include $className.".class.php";
});

use Mediator\User;

$robert = new User(‘Robert‘);

$join = new User(‘Join‘);

$robert->sendMessage(‘hello, Join‘);

$join->sendMessage(‘hello, Robert‘);

 

设计模式之中介者模式(php实现)

标签:ati   car   设计   发送   reg   github   static   use   oom   

原文地址:https://www.cnblogs.com/zhouqi666/p/9164015.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!