<?php
declare(strict_types=1);
// php 技术群:781742505
// 同类型的对象通过中介互动。
interface ChatRoomMediator
{
public function showMessage(User $user, string $message);
}
// Mediator
class ChatRoom implements ChatRoomMediator
{
public function showMessage(User $user, string $message)
{
$time = date('M d, y H:i');
$sender = $user->getName();
echo $time.'['.$sender.']:'.$message;
}
}
class User
{
protected $name;
protected $chatMediator;
public function __construct(string $name, ChatRoomMediator $chatMediator)
{
$this->name = $name;
$this->chatMediator = $chatMediator;
}
public function getName()
{
return $this->name;
}
public function send($message)
{
$this->chatMediator->showMessage($this, $message);
}
}
$mediator = new ChatRoom();
$john = new User('John Doe', $mediator);
$jane = new User('Jane Doe', $mediator);
$john->send('Hi there!');
$jane->send('Hey!');
// Output will be
// Feb 14, 10:58 [John]: Hi there!
// Feb 14, 10:58 [Jane]: Hey!
中介者模式
最新推荐文章于 2024-09-20 21:23:30 发布