分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

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

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

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

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

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

<?phpnamespace 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(客户端)

<?phpspl_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实现)

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved