PHP 设计模式系列 -- 委托模式( Delegation)

php中文网
发布: 2016-06-23 13:18:58
原创
1287人浏览过

1、模式定义

委托是对一个类的功能进行扩展和复用的方法。它的做法是:写一个附加的类提供附加的功能,并使用原来的类的实例提供原有的功能。

假设我们有一个 TeamLead 类,将其既定任务委托给一个关联辅助对象 JuniorDeveloper 来完成:本来 TeamLead 处理 writeCode 方法,Usage 调用 TeamLead 的该方法,但现在 TeamLead 将 writeCode 的实现委托给 JuniorDeveloper 的 writeBadCode 来实现,但 Usage 并没有感知在执行 writeBadCode 方法。

2、UML类图

3、示例代码

Usage.php

百灵大模型
百灵大模型

蚂蚁集团自研的多模态AI大模型系列

百灵大模型 177
查看详情 百灵大模型
<?phpnamespace DesignPatterns\More\Delegation;// 初始化 TeamLead 并委托辅助者 JuniorDeveloper$teamLead = new TeamLead(new JuniorDeveloper());// TeamLead 将编写代码的任务委托给 JuniorDeveloperecho $teamLead->writeCode();
登录后复制

TeamLead.php

立即学习PHP免费学习笔记(深入)”;

<?phpnamespace DesignPatterns\More\Delegation;/** * TeamLead类 * @package DesignPatterns\Delegation * `TeamLead` 类将工作委托给 `JuniorDeveloper` */class TeamLead{    /** @var JuniorDeveloper */    protected $slave;    /**     * 在构造函数中注入初级开发者JuniorDeveloper     * @param JuniorDeveloper $junior     */    public function __construct(JuniorDeveloper $junior)    {        $this->slave = $junior;    }    /**     * TeamLead 喝咖啡, JuniorDeveloper 工作     * @return mixed     */    public function writeCode()    {        return $this->slave->writeBadCode();    }}
登录后复制

JuniorDeveloper.php

<?phpnamespace DesignPatterns\More\Delegation;/** * JuniorDeveloper 类 * @package DesignPatterns\Delegation */class JuniorDeveloper{    public function writeBadCode()    {        return "Some junior developer generated code...";    }}
登录后复制

4、测试代码

Tests/DelegationTest.php

<?phpnamespace DesignPatterns\More\Delegation\Tests;use DesignPatterns\More\Delegation;/** * DelegationTest 用于测试委托模式 */class DelegationTest extends \PHPUnit_Framework_TestCase{    public function testHowTeamLeadWriteCode()    {        $junior = new Delegation\JuniorDeveloper();        $teamLead = new Delegation\TeamLead($junior);        $this->assertEquals($junior->writeBadCode(), $teamLead->writeCode());    }}
登录后复制
PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号