PHP常用设计模式之委托设计模式_PHP
May 27, 2016 am 10:37 AM模式定义
委托是对一个类的功能进行扩展和复用的方法。它的做法是:写一个附加的类提供附加的功能,并使用原来的类的实例提供原有的功能。
假设我们有一个 TeamLead 类,将其既定任务委托给一个关联辅助对象 JuniorDeveloper 来完成:本来 TeamLead 处理 writeCode 方法,Usage 调用 TeamLead 的该方法,但现在 TeamLead 将 writeCode 的实现委托给 JuniorDeveloper 的 writeBadCode 来实现,但 Usage 并没有感知在执行 writeBadCode 方法。
设计了一个cd类,类中有mp3播放模式,和mp4播放模式
改进前,使用cd类的播放模式,需要在实例化的类中去判断选择什么方式的播放模式
改进后,播放模式当做一个参数传入playList函数中,就自动能找到对应需要播放的方法。
一,未改进前
<?php //使用委托模式之前,调用cd类,选择cd播放模式是复杂的选择过程 class cd { protected $cdInfo = array(); public function addSong($song) { $this->cdInfo[$song] = $song; } public function playMp3($song) { return $this->cdInfo[$song] . '.mp3'; } public function playMp4($song) { return $this->cdInfo[$song] . '.mp4'; } } $oldCd = new cd; $oldCd->addSong("1"); $oldCd->addSong("2"); $oldCd->addSong("3"); $type = 'mp3'; if ($type == 'mp3') { $oldCd->playMp3(); } else { $oldCd->playMp4(); }
二、通过委托模式,改进后的cd类
<?php namespace Tools; /* 委托模式 去除核心对象中的判决和复杂功能性 */ //委托接口 interface Delegate{ public function playList($list,$song); } //mp3处理类 class mp3 implements Delegate{ public function playList($list,$song){ return $list[$song].'.mp3'; } } //mp4处理类 class mp4 implements Delegate{ public function playList($list, $song) { return $list[$song].'.mp4'; } } class cdDelegate{ protected $cdInfo = array(); public function addSong($song){ $this->cdInfo[$song] = $song; } public function play($type,$song){ $name = '\Tools\\'.$type; $obj = new $name; return $obj->playList($this->cdInfo,$song); } } $newCd = new cdDelegate(); $newCd->addSong("1"); $newCd->addSong("2"); $newCd->addSong("3"); echo $newCd->play('mp3','1');//只要传递参数就能知道需要选择何种播放模式
以上内容给大家介绍了PHP委托设计模式实例详解,希望对大家有所帮助。

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey
