PHP设计模式之委托模式(Delegation)代码实例大全(33)

目的

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

例子

请阅读 JuniorDeveloper.php,TeamLead.php 中的代码,而后在 Usage.php 中结合在一块儿。laravel

★官方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 互联网架构师成长之路*「设计模式」终极指南sql

PHP 互联网架构师 50K 成长指南+行业问题解决总纲(持续更新)shell

面试10家公司,收获9个offer,2020年PHP 面试问题设计模式

★若是喜欢个人文章,想与更多资深开发者一块儿交流学习的话,获取更多大厂面试相关技术咨询和指导,欢迎加入咱们的群啊,暗号:phpzh服务器

2020年最新PHP进阶教程,全系列!架构

内容不错的话但愿你们支持鼓励下点个赞/喜欢,欢迎一块儿来交流;另外若是有什么问题 建议 想看的内容能够在评论提出并发