委托模式(Delegation)

目的

在委托模式的示例里,一个对象将它要执行的任务委派给与之关联的帮助对象去执行。在示例中,「组长」声明了 writeCode 方法并使用它,其实「组长」把 writeCode 委托给「菜鸟开发者」的 writeBadCode 方法做了。这种反转责任的做法隐藏了其内部执行 writeBadCode 的细节。

例子

请阅读 JuniorDeveloper.php,TeamLead.php 中的代码,然后在Usage.php 中结合在一起。

UML 类图

file

代码

你可以在 GitHub 上找到这些代码

TeamLead.php

  1. <?php
  2. namespace DesignPatterns\More\Delegation;
  3. class TeamLead
  4. {
  5. /**
  6. * @var JuniorDeveloper
  7. */
  8. private $junior;
  9. /**
  10. * @param JuniorDeveloper $junior
  11. */
  12. public function __construct(JuniorDeveloper $junior)
  13. {
  14. $this->junior = $junior;
  15. }
  16. public function writeCode(): string
  17. {
  18. return $this->junior->writeBadCode();
  19. }
  20. }

JuniorDeveloper.php

  1. <?php
  2. namespace DesignPatterns\More\Delegation;
  3. class JuniorDeveloper
  4. {
  5. public function writeBadCode(): string
  6. {
  7. return 'Some junior developer generated code...';
  8. }
  9. }

测试

Tests/DelegationTest.php

  1. <?php
  2. namespace DesignPatterns\More\Delegation\Tests;
  3. use DesignPatterns\More\Delegation;
  4. use PHPUnit\Framework\TestCase;
  5. class DelegationTest extends TestCase
  6. {
  7. public function testHowTeamLeadWriteCode()
  8. {
  9. $junior = new Delegation\JuniorDeveloper();
  10. $teamLead = new Delegation\TeamLead($junior);
  11. $this->assertEquals($junior->writeBadCode(), $teamLead->writeCode());
  12. }
  13. }