zoukankan      html  css  js  c++  java
  • 设计模式之中介者模式(php实现)

    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 MediatorUser;
    
    $robert = new User('Robert');
    
    $join = new User('Join');
    
    $robert->sendMessage('hello, Join');
    
    $join->sendMessage('hello, Robert');
  • 相关阅读:
    每天问自己十个问题
    FreeBSD入门安装及汉化
    商人的10条赚钱规则
    端口扫描程序nmap使用手册
    canvas
    表单2.0
    H5数据保存之storage
    Linux基础命令2
    Linux文件权限与修改
    Linux基础命令1
  • 原文地址:https://www.cnblogs.com/zhouqi666/p/9164015.html
Copyright © 2011-2022 走看看