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