Detailed explanation of the delegation pattern of PHP design patterns

*文
Release: 2023-03-19 10:14:01
Original
1476 people have browsed it

委托是对一个类的功能进行扩展和复用的方法。它的做法是:写一个附加的类提供附加的功能,并使用原来的类的实例提供原有的功能,接下来通过本文给大家介绍PHP委托设计模式实例详解,感兴趣的朋友一起学习吧。希望对大家有所帮助。

模式定义

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

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

设计了一个cd类,类中有mp3播放模式,和mp4播放模式
改进前,使用cd类的播放模式,需要在实例化的类中去判断选择什么方式的播放模式
改进后,播放模式当做一个参数传入playList函数中,就自动能找到对应需要播放的方法。

一,未改进前

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(); 
}
Copy after login

二、通过委托模式,改进后的cd类

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');//只要传递参数就能知道需要选择何种播放模式
Copy after login

相关推荐:

详解PHP设计模式之备忘录模式

详解PHP设计模式之建造者模式

PHP设计模式之迭代器模式详解

The above is the detailed content of Detailed explanation of the delegation pattern of PHP design patterns. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!