W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
這種模式提供了一種簡單的解耦多組件之間的協(xié)同工作方式。如果你有一個(gè)“智能中心”,比如控制器(但不是 MVC 的意義上),它是觀察者的一個(gè)很好的替代品。
所有組件(稱為同事)僅與 Mediator 接口耦合,這是一件好事,因?yàn)樵?OOP 中,一個(gè)好朋友勝過多個(gè)。這是這種模式的關(guān)鍵特征。
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'); } }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: