PHP设计模式 - 委托模式

2019-04-25 16:15 By 茹茹 3217 1 1

【一】模式定义

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

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


【二】UML类图

image.png


【三】示例代码

Usage.php

<?php

namespace DesignPatterns\More\Delegation;

// 初始化 TeamLead 并委托辅助者 JuniorDeveloper
$teamLead = new TeamLead(new JuniorDeveloper());

// TeamLead 将编写代码的任务委托给 JuniorDeveloper
echo $teamLead->writeCode();

TeamLead.php

<?php

namespace 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

<?php

namespace DesignPatterns\More\Delegation;

/**
 * JuniorDeveloper 类
 * @package DesignPatterns\Delegation
 */
class JuniorDeveloper
{
    public function writeBadCode()
    {
        return "Some junior developer generated code...";
    }
}



【四】测试代码

Tests/DelegationTest.php

<?php

namespace 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());
    }
}
注:本文转载自 Laravel学院 ,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。
如有侵权行为,请联系我们,我们会及时删除。

评 论

rdgztest_XIFZPJ 8 2019-05-09 15:49
vvvvvvvvvvvvvv

View in WeChat

Others Discussion

  • PHP没你想的那么差
    Posted on 2021-12-17 15:40
  • Mysql联合索引的最左前缀匹配原则
    Posted on 2018-08-25 15:00
  • 2016年云计算热词
    Posted on 2019-06-12 17:53
  • 分布式架构之「 数据分布」
    Posted on 2019-11-14 10:00
  • 巧用CAS解决数据一致性问题
    Posted on 2019-03-07 11:55
  • PHP扩展ImageMagick安装
    Posted on 2022-11-11 11:16
  • 通过信鸽来解释HTTPS
    Posted on 2018-10-22 13:56
  • HTTP和HTTPS的区别
    Posted on 2020-08-10 23:00