目的
在委托模式的示例里,一個物件將它要執行的任務委派給與之關聯的幫助物件去執行,在示例中,「組長」宣告了 writeCode 方法并使用它,其實「組長」把 writeCode 委托給「菜鳥開發者」的 writeBadCode 方法做了,這種反轉責任的做法隱藏了其內部執行 writeBadCode 的細節,
例子
請閱讀 JuniorDeveloper.php,TeamLead.php 中的代碼,然后在 Usage.php 中結合在一起,

★官方PHP高級學習交流社群「點擊」管理整理了一些資料,BAT等一線大廠進階知識體系備好(相關學習資料以及筆面試題)以及不限于:分布式架構、高可擴展、高性能、高并發、服務器性能調優、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql優化、shell腳本、Docker、微服務、Nginx等多個知識點高級進階干貨
代碼
- 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 互聯網架構師成長之路*「設計模式」終極指南
PHP 互聯網架構師 50K 成長指南+行業問題解決總綱(持續更新)
面試10家公司,識訓9個offer,2020年PHP 面試問題
★如果喜歡我的文章,想與更多資深開發者一起交流學習的話,獲取更多大廠面試相關技術咨詢和指導,歡迎加入我們的群啊,暗號:phpzh
2020年最新PHP進階教程,全系列!

內容不錯的話希望大家支持鼓勵下點個贊/喜歡,歡迎一起來交流;另外如果有什么問題 建議 想看的內容可以在評論提出
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/106255.html
標籤:PHP
