阅读(843)
赞(0)
PHP 中介者模式
2022-03-22 09:49:13 更新
目的
这种模式提供了一种简单的解耦多组件之间的协同工作方式。如果你有一个“智能中心”,比如控制器(但不是 MVC 的意义上),它是观察者的一个很好的替代品。
所有组件(称为同事)仅与 Mediator 接口耦合,这是一件好事,因为在 OOP 中,一个好朋友胜过多个。这是这种模式的关键特征。
UML 图
代码
Mediator.php
<?php declare(strict_types=1); namespace DesignPatterns\Behavioral\Mediator; interface Mediator { public function getUser(string $username): string; }
Colleague.php
<?php declare(strict_types=1); namespace DesignPatterns\Behavioral\Mediator; abstract class Colleague { protected Mediator $mediator; public function setMediator(Mediator $mediator) { $this->mediator = $mediator; } }
Ui.php
<?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
<?php declare(strict_types=1); namespace DesignPatterns\Behavioral\Mediator; class UserRepository extends Colleague { public function getUserName(string $user): string { return 'User: ' . $user; } }
UserRepositoryUiMediator.php
<?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); } }
测试
Tests/MediatorTest.php
<?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'); } }