PHP面向对象程序设计组合模式与装饰模式详解
本文实例讲述了PHP面向对象程序设计组合模式与装饰模式。分享给大家供大家参考,具体如下:
组合模式
定义:组合模式定义了一个单根继承体系,使具有截然不同职责的集合可以并肩工作。
一个军队的案例,
<?php abstractclassUnit{//个体 abstractfunctionbombardStrength(); } classArcherextendsUnit{//弓箭手 functionbombardStrength(){ return4; } } classLaserCannonUnitextendsUnit{//火炮手 functionbombardStrength(){ return44; } } ?>
军队整合成员,输出火力
<?php abstractclassUnit{ abstractfunctionbombardStrength(); } classArcherextendsUnit{ functionbombardStrength(){ return4; } } classLaserCannonUnitextendsUnit{ functionbombardStrength(){ return44; } } classArmy{//军队 private$units=array();//定义私有属性个体集 functionaddUnit(Unit$unit){//添加成员 array_push($this->units,$unit); } functionbombardStrength(){//火力 $ret=0; foreach($this->unitsas$unit){ $ret+=$unit->bombardStrength(); } return$ret; } } $unit1=newArcher(); $unit2=newLaserCannonUnit(); $army=newArmy(); $army->addUnit($unit1); $army->addUnit($unit2); print$army->bombardStrength();//输出火力 ?>
output:
48
军队进一步整合其他军队
<?php abstractclassUnit{ abstractfunctionbombardStrength(); } classArcherextendsUnit{ functionbombardStrength(){ return4; } } classLaserCannonUnitextendsUnit{ functionbombardStrength(){ return44; } } classArmy{ private$units=array(); private$armies=array(); functionaddUnit(Unit$unit){ array_push($this->units,$unit); } functionaddArmy(Army$army){ array_push($this->armies,$army); } functionbombardStrength(){ $ret=0; foreach($this->unitsas$unit){ $ret+=$unit->bombardStrength(); } foreach($this->armiesas$army){ $ret+=$army->bombardStrength(); } return$ret; } } $unit1=newArcher(); $unit2=newLaserCannonUnit(); $army=newArmy(); $army->addUnit($unit1); $army->addUnit($unit2); print$army->bombardStrength(); print"\n"; $army2=clone$army;//克隆军队 $army->addArmy($army2); print$army->bombardStrength(); print"\n"; ?>
output:
48
96
更好的方式,支持新增,移除等等其他功能。
<?php abstractclassUnit{ abstractfunctionaddUnit(Unit$unit); abstractfunctionremoveUnit(Unit$unit); abstractfunctionbombardStrength(); } classArmyextendsUnit{//军队 private$units=array(); functionaddUnit(Unit$unit){ if(in_array($unit,$this->units,true)){//$this用于调用正常的属性或方法,self调用静态的方法,属性或者常量 return; } $this->units[]=$unit; } functionremoveUnit(Unit$unit){ //>=php5.3 $this->units=array_udiff($this->units,array($unit), function($a,$b){return($a===$b)?0:1;}); //<php5.3 //$this->units=array_udiff($this->units,array($unit), //create_function('$a,$b','return($a===$b)?0:1;')); //对象数组,create_function,创建函数 } functionbombardStrength(){ $ret=0; foreach($this->unitsas$unit){ $ret+=$unit->bombardStrength(); } return$ret; } } //quickexampleclasses classTankextendsUnit{//坦克 functionaddUnit(Unit$unit){} functionremoveUnit(Unit$unit){} functionbombardStrength(){ return4; } } classSoldierextendsUnit{//士兵 functionaddUnit(Unit$unit){} functionremoveUnit(Unit$unit){} functionbombardStrength(){ return8; } } $tank=newTank(); $tank2=newTank(); $soldier=newSoldier(); $army=newArmy(); $army->addUnit($soldier); $army->addUnit($tank); $army->addUnit($tank2); print_r($army); print$army->bombardStrength()."\n"; $army->removeUnit($soldier); print_r($army); print$army->bombardStrength()."\n"; ?>
output:
ArmyObject ( [units:Army:private]=>Array ( [0]=>SoldierObject ( ) [1]=>TankObject ( ) [2]=>TankObject ( ) ) ) 16 ArmyObject ( [units:Army:private]=>Array ( [1]=>TankObject ( ) [2]=>TankObject ( ) ) ) 8
添加异常处理
<?php abstractclassUnit{ abstractfunctionaddUnit(Unit$unit); abstractfunctionremoveUnit(Unit$unit); abstractfunctionbombardStrength(); } classArmyextendsUnit{ private$units=array(); functionaddUnit(Unit$unit){ if(in_array($unit,$this->units,true)){ return; } $this->units[]=$unit; } functionremoveUnit(Unit$unit){ //>=php5.3 //$this->units=array_udiff($this->units,array($unit), //function($a,$b){return($a===$b)?0:1;}); //<php5.3 $this->units=array_udiff($this->units,array($unit), create_function('$a,$b','return($a===$b)?0:1;')); } functionbombardStrength(){ $ret=0; foreach($this->unitsas$unit){ $ret+=$unit->bombardStrength(); } return$ret; } } classUnitExceptionextendsException{} classArcherextendsUnit{ functionaddUnit(Unit$unit){ thrownewUnitException(get_class($this)."isaleaf"); } functionremoveUnit(Unit$unit){ thrownewUnitException(get_class($this)."isaleaf"); } functionbombardStrength(){ return4; } } $archer=newArcher(); $archer2=newArcher(); $archer->addUnit($archer2); ?>
output:
Fatalerror:Uncaughtexception'UnitException'withmessage'Archerisaleaf'
点评:组合模式中的一切类都共享同一个父类型,可以轻松地在设计中添加新的组合对象或局部对象,而无需大范围地修改代码。
最终的效果,逐步优化(完美):
<?php classUnitExceptionextendsException{} abstractclassUnit{ abstractfunctionbombardStrength(); functionaddUnit(Unit$unit){ thrownewUnitException(get_class($this)."isaleaf"); } functionremoveUnit(Unit$unit){ thrownewUnitException(get_class($this)."isaleaf"); } } classArcherextendsUnit{ functionbombardStrength(){ return4; } } classLaserCannonUnitextendsUnit{ functionbombardStrength(){ return44; } } classArmyextendsUnit{ private$units=array(); functionaddUnit(Unit$unit){ if(in_array($unit,$this->units,true)){ return; } $this->units[]=$unit; } functionremoveUnit(Unit$unit){ //>=php5.3 //$this->units=array_udiff($this->units,array($unit), //function($a,$b){return($a===$b)?0:1;}); //<php5.3 $this->units=array_udiff($this->units,array($unit), create_function('$a,$b','return($a===$b)?0:1;')); } functionbombardStrength(){ $ret=0; foreach($this->unitsas$unit){ $ret+=$unit->bombardStrength(); } return$ret; } } //createanarmy $main_army=newArmy(); //addsomeunits $main_army->addUnit(newArcher()); $main_army->addUnit(newLaserCannonUnit()); //createanewarmy $sub_army=newArmy(); //addsomeunits $sub_army->addUnit(newArcher()); $sub_army->addUnit(newArcher()); $sub_army->addUnit(newArcher()); //addthesecondarmytothefirst $main_army->addUnit($sub_army); //allthecalculationshandledbehindthescenes print"attackingwithstrength:{$main_army->bombardStrength()}\n"; ?>
output:
attackingwithstrength:60
更牛逼的组合处理,
<?php abstractclassUnit{ functiongetComposite(){ returnnull; } abstractfunctionbombardStrength(); } abstractclassCompositeUnitextendsUnit{//抽象类继承抽象类 private$units=array(); functiongetComposite(){ return$this; } protectedfunctionunits(){ return$this->units; } functionremoveUnit(Unit$unit){ //>=php5.3 //$this->units=array_udiff($this->units,array($unit), //function($a,$b){return($a===$b)?0:1;}); //<php5.3 $this->units=array_udiff($this->units,array($unit), create_function('$a,$b','return($a===$b)?0:1;')); } functionaddUnit(Unit$unit){ if(in_array($unit,$this->units,true)){ return; } $this->units[]=$unit; } } classArmyextendsCompositeUnit{ functionbombardStrength(){ $ret=0; foreach($this->unitsas$unit){ $ret+=$unit->bombardStrength(); } return$ret; } } classArcherextendsUnit{ functionbombardStrength(){ return4; } } classLaserCannonUnitextendsUnit{ functionbombardStrength(){ return44; } } classUnitScript{ staticfunctionjoinExisting(Unit$newUnit, Unit$occupyingUnit){//静态方法,直接通过类名来使用 $comp; if(!is_null($comp=$occupyingUnit->getComposite())){//军队合并处理 $comp->addUnit($newUnit); }else{//士兵合并处理 $comp=newArmy(); $comp->addUnit($occupyingUnit); $comp->addUnit($newUnit); } return$comp; } } $army1=newArmy(); $army1->addUnit(newArcher()); $army1->addUnit(newArcher()); $army2=newArmy(); $army2->addUnit(newArcher()); $army2->addUnit(newArcher()); $army2->addUnit(newLaserCannonUnit()); $composite=UnitScript::joinExisting($army2,$army1); print_r($composite); ?>
output:
ArmyObject ( [units:CompositeUnit:private]=>Array ( [0]=>ArcherObject ( ) [1]=>ArcherObject ( ) [2]=>ArmyObject ( [units:CompositeUnit:private]=>Array ( [0]=>ArcherObject ( ) [1]=>ArcherObject ( ) [2]=>LaserCannonUnitObject ( ) ) ) ) )
点评:Unit基础,CompositeUnit复合中实现add与remove。军队继承Composite,射手继承Archer。这样射手中就不会有多余的add与remove方法了。
装饰模式
装饰模式帮助我们改变具体组件的功能。
看例子
<?php abstractclassTile{//砖瓦 abstractfunctiongetWealthFactor();//获取财富 } classPlainsextendsTile{//平原 private$wealthfactor=2; functiongetWealthFactor(){ return$this->wealthfactor; } } classDiamondPlainsextendsPlains{//钻石地段 functiongetWealthFactor(){ returnparent::getWealthFactor()+2; } } classPollutedPlainsextendsPlains{//污染地段 functiongetWealthFactor(){ returnparent::getWealthFactor()-4; } } $tile=newPollutedPlains(); print$tile->getWealthFactor(); ?>
output:
-2
点评:不具有灵活性,我们不能同时获得钻石与被污染的土地的资金情况。
装饰模式使用组合和委托而不是只使用继承来解决功能变化的问题。
看例子:
<?php abstractclassTile{ abstractfunctiongetWealthFactor(); } classPlainsextendsTile{ private$wealthfactor=2; functiongetWealthFactor(){ return$this->wealthfactor; } } abstractclassTileDecoratorextendsTile{//装饰 protected$tile; function__construct(Tile$tile){ $this->tile=$tile; } } classDiamondDecoratorextendsTileDecorator{//钻石装饰 functiongetWealthFactor(){ return$this->tile->getWealthFactor()+2; } } classPollutionDecoratorextendsTileDecorator{//污染装饰 functiongetWealthFactor(){ return$this->tile->getWealthFactor()-4; } } $tile=newPlains(); print$tile->getWealthFactor();//2 $tile=newDiamondDecorator(newPlains()); print$tile->getWealthFactor();//4 $tile=newPollutionDecorator( newDiamondDecorator(newPlains())); print$tile->getWealthFactor();//0 ?>
output:
2
4
0
点评:这个模型具有扩展性。我们不需要创建DiamondPollutionPlains对象就可以构建一个钻石被污染的对象。
一个更逼真的例子
<?php classRequestHelper{}//请求助手 abstractclassProcessRequest{//进程请求 abstractfunctionprocess(RequestHelper$req); } classMainProcessextendsProcessRequest{//主进程 functionprocess(RequestHelper$req){ print__CLASS__.":doingsomethingusefulwithrequest\n"; } } abstractclassDecorateProcessextendsProcessRequest{//装饰进程 protected$processrequest; function__construct(ProcessRequest$pr){//引用对象,委托 $this->processrequest=$pr; } } classLogRequestextendsDecorateProcess{//日志请求 functionprocess(RequestHelper$req){ print__CLASS__.":loggingrequest\n";//当前类,有点递归的感觉 $this->processrequest->process($req); } } classAuthenticateRequestextendsDecorateProcess{//认证请求 functionprocess(RequestHelper$req){ print__CLASS__.":authenticatingrequest\n"; $this->processrequest->process($req); } } classStructureRequestextendsDecorateProcess{//组织结构请求 functionprocess(RequestHelper$req){ print__CLASS__.":structuringrequest\n"; $this->processrequest->process($req); } } $process=newAuthenticateRequest(newStructureRequest( newLogRequest( newMainProcess() )));//这样可以很灵活的组合进程的关系,省去很多重复的继承 $process->process(newRequestHelper()); print_r($process); ?>
output:
AuthenticateRequest:authenticatingrequest StructureRequest:structuringrequest LogRequest:loggingrequest MainProcess:doingsomethingusefulwithrequest AuthenticateRequestObject ( [processrequest:protected]=>StructureRequestObject ( [processrequest:protected]=>LogRequestObject ( [processrequest:protected]=>MainProcessObject ( ) ) ) )
点评:这里有一种递归的感觉,一层调用一层。模式是牛人总结出来用于灵活的解决一些现实问题的。牛!给开发多一点思路。
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。