目的
在委託模式的示例裏,一個對象將它要執行的任務委派給與之關聯的幫助對象去執行。在示例中,「組長」聲明瞭 writeCode 方法並使用它,其實「組長」把 writeCode 委託給「菜鳥開發者」的 writeBadCode 方法做了。這種反轉責任的做法隱藏了其內部執行 writeBadCode 的細節。
例子
請閱讀 JuniorDeveloper.php,TeamLead.php 中的代碼,然後在 Usage.php 中結合在一起。
代碼
- TeamLead.php
<?php
namespace DesignPatterns\More\Delegation;
class TeamLead
{
/**
* @var JuniorDeveloper
*/
private $junior;
/**
* @param JuniorDeveloper $junior
*/
public function __construct(JuniorDeveloper $junior)
{
$this->junior = $junior;
}
public function writeCode(): string
{
return $this->junior->writeBadCode();
}
}
- JuniorDeveloper.php
<?php
namespace DesignPatterns\More\Delegation;
class JuniorDeveloper
{
public function writeBadCode(): string
{
return 'Some junior developer generated code...';
}
}
測試
- Tests/DelegationTest.php
<?php
namespace DesignPatterns\More\Delegation\Tests;
use DesignPatterns\More\Delegation;
use PHPUnit\Framework\TestCase;
class DelegationTest extends TestCase
{
public function testHowTeamLeadWriteCode()
{
$junior = new Delegation\JuniorDeveloper();
$teamLead = new Delegation\TeamLead($junior);
$this->assertEquals($junior->writeBadCode(), $teamLead->writeCode());
}
}
PHP 互聯網架構師 50K 成長指南+行業問題解決總綱(持續更新)
面試10家公司,收穫9個offer,2020年PHP 面試問題
★如果喜歡我的文章,想與更多資深開發者一起交流學習的話,獲取更多大廠面試相關技術諮詢和指導,歡迎加入我們的羣啊,暗號:phpzh
內容不錯的話希望大家支持鼓勵下點個贊/喜歡,歡迎一起來交流;另外如果有什麼問題 建議 想看的內容可以在評論提出