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