PHP设计模式系列--委托模式(Delegation)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了PHP设计模式系列--委托模式(Delegation),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2030字,纯文字阅读大概需要3分钟。
内容图文
![PHP设计模式系列--委托模式(Delegation)](/upload/InfoBanner/zyjiaocheng/205/c2a51d79e59c41be87bc8094feccc59f.jpg)
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
<?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设计模式系列--委托模式(Delegation)全部内容,希望文章能够帮你解决PHP设计模式系列--委托模式(Delegation)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。