3.5. Mediator (Mediador)¶
3.5.1. Objetivo¶
Este padrão provê uma forma fácil para desacoplar muitos componentes trabalhando juntos. Ele é uma boa alternativa ao Observer SE você tem uma “inteligência central”, como um controlador (mas não no sentido do MVC).
Todos componentes (chamados Colleague - em inglês, Colega) são acoplados apenas ao Mediator e é uma coisa boa porque, em POO (Programação Orientada a Objetos), uma boa amiga é melhor que muitas. Esta é a característica-chave deste padrão.
3.5.2. Diagrama UML¶

3.5.3. Código¶
Você também pode encontrar este código no GitHub
Mediator.php
1 2 3 4 5 6 7 8 9 10 | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Mediator;
interface Mediator
{
public function getUser(string $username): string;
}
|
Colleague.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Mediator;
abstract class Colleague
{
protected Mediator $mediator;
final public function setMediator(Mediator $mediator)
{
$this->mediator = $mediator;
}
}
|
Ui.php
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Mediator;
class Ui extends Colleague
{
public function outputUserInfo(string $username)
{
echo $this->mediator->getUser($username);
}
}
|
UserRepository.php
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Mediator;
class UserRepository extends Colleague
{
public function getUserName(string $user): string
{
return 'User: ' . $user;
}
}
|
UserRepositoryUiMediator.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Mediator;
class UserRepositoryUiMediator implements Mediator
{
public function __construct(private UserRepository $userRepository, private Ui $ui)
{
$this->userRepository->setMediator($this);
$this->ui->setMediator($this);
}
public function printInfoAbout(string $user)
{
$this->ui->outputUserInfo($user);
}
public function getUser(string $username): string
{
return $this->userRepository->getUserName($username);
}
}
|
3.5.4. Teste¶
Tests/MediatorTest.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php
declare(strict_types=1);
namespace DesignPatterns\Tests\Mediator\Tests;
use DesignPatterns\Behavioral\Mediator\Ui;
use DesignPatterns\Behavioral\Mediator\UserRepository;
use DesignPatterns\Behavioral\Mediator\UserRepositoryUiMediator;
use PHPUnit\Framework\TestCase;
class MediatorTest extends TestCase
{
public function testOutputHelloWorld()
{
$mediator = new UserRepositoryUiMediator(new UserRepository(), new Ui());
$this->expectOutputString('User: Dominik');
$mediator->printInfoAbout('Dominik');
}
}
|