• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

php 搞代码 3年前 (2022-01-23) 22次浏览 已收录 0个评论

1、模式定义

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

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

2、UML类图

3、示例代码

Usage.php

<?phpnamespace DesignPatterns\More\Delegation;// 初始化 TeamLead 并委托辅助者 JuniorDeveloper$teamLead = new TeamLead(new JuniorDeveloper());// TeamLead 将编写代码的任务委托给 JuniorDeveloperecho $teamLead->writeCode();

TeamLead.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

5本文来源gao!daima.com搞$代!码#网#

搞代gaodaima码
<?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());    }}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PHP 设计模式系列 — 委托模式( Delegation)
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址