php 委托模式,php 设计模式- 委托模式

委托模式

通过分配或委托其他对象,委托设计模式能够去除核心对象中的判决和复杂的功能性。

应用场景

设计了一个cd类,类中有mp3播放模式,和mp4播放模式

改进前,使用cd类的播放模式,需要在实例化的类中去判断选择什么方式的播放模式

改进后,播放模式当做一个参数传入playList函数中,就自动能找到对应需要播放的方法。

代码:cd类,未改进之前,选择播放模式是一种痛苦的事情 。

//委托模式-去除核心对象中的判决和复杂的功能性

//使用委托模式之前,调用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类

classcdDelegate{

protected$cdInfo=array();

publicfunctionaddSong($song){

$this->cdInfo[$song]=$song;

}

publicfunctionplay($type,$song){

$obj=new$type;

return$obj->playList($this->cdInfo,$song);

}

}

classmp3{

publicfunctionplayList($list){

return$list[$song];

}

}

classmp4{

publicfunctionplayList($list){

return$list[$song];

}

}

$newCd=newcd;

$newCd->addSong("1");

$newCd->addSong("2");

$newCd->addSong("3");

$type='mp3';

$oldCd->play('mp3','1');//只要传递参数就能知道需要选择何种播放模式

参考:《PHP设计模式》Aaron Saray著

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值