PHP面向对象程序设计组合模式与装饰模式详解
本文实例讲述了php面向对象程序设计组合模式与装饰模式。分享给大家供大家参考,具体如下:
组合模式
定义:组合模式定义了一个单根继承体系,使具有截然不同职责的集合可以并肩工作。
一个军队的案例,
<?php abstract class unit { // 个体 abstract function bombardstrength(); } class archer extends unit { // 弓箭手 function bombardstrength() { return 4; } } class lasercannonunit extends unit { // 火炮手 function bombardstrength() { return 44; } } ?>
军队整合成员,输出火力
<?php abstract class unit { abstract function bombardstrength(); } class archer extends unit { function bombardstrength() { return 4; } } class lasercannonunit extends unit { function bombardstrength() { return 44; } } class army { // 军队 private $units = array(); // 定义私有属性 个体集 function addunit( unit $unit ) { // 添加成员 array_push( $this->units, $unit ); } function bombardstrength() { // 火力 $ret = 0; foreach( $this->units as $unit ) { $ret += $unit->bombardstrength(); } return $ret; } } $unit1 = new archer(); $unit2 = new lasercannonunit(); $army = new army(); $army->addunit( $unit1 ); $army->addunit( $unit2 ); print $army->bombardstrength(); // 输出火力 ?>
output:
48
军队进一步整合其他军队
<?php abstract class unit { abstract function bombardstrength(); } class archer extends unit { function bombardstrength() { return 4; } } class lasercannonunit extends unit { function bombardstrength() { return 44; } } class army { private $units = array(); private $armies= array(); function addunit( unit $unit ) { array_push( $this->units, $unit ); } function addarmy( army $army ) { array_push( $this->armies, $army ); } function bombardstrength() { $ret = 0; foreach( $this->units as $unit ) { $ret += $unit->bombardstrength(); } foreach( $this->armies as $army ) { $ret += $army->bombardstrength(); } return $ret; } } $unit1 = new archer(); $unit2 = new lasercannonunit(); $army = new army(); $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 abstract class unit { abstract function addunit( unit $unit ); abstract function removeunit( unit $unit ); abstract function bombardstrength(); } class army extends unit { // 军队 private $units = array(); function addunit( unit $unit ) { if ( in_array( $unit, $this->units, true ) ) { // $this用于调用正常的属性或方法,self调用静态的方法,属性或者常量 return; } $this->units[] = $unit; } function removeunit( unit $unit ) { // >= php 5.3 $this->units = array_udiff( $this->units, array( $unit ), function( $a, $b ) { return ($a === $b)?0:1; } ); // < php 5.3 // $this->units = array_udiff( $this->units, array( $unit ), // create_function( '$a,$b', 'return ($a === $b)?0:1;' ) ); // 对象数组,create_function,创建函数 } function bombardstrength() { $ret = 0; foreach( $this->units as $unit ) { $ret += $unit->bombardstrength(); } return $ret; } } // quick example classes class tank extends unit { // 坦克 function addunit( unit $unit ) {} function removeunit( unit $unit ) {} function bombardstrength() { return 4; } } class soldier extends unit { // 士兵 function addunit( unit $unit ) {} function removeunit( unit $unit ) {} function bombardstrength() { return 8; } } $tank = new tank(); $tank2 = new tank(); $soldier = new soldier(); $army = new army(); $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:
army object ( [units:army:private] => array ( [0] => soldier object ( ) [1] => tank object ( ) [2] => tank object ( ) ) ) 16 army object ( [units:army:private] => array ( [1] => tank object ( ) [2] => tank object ( ) ) ) 8
添加异常处理
<?php abstract class unit { abstract function addunit( unit $unit ); abstract function removeunit( unit $unit ); abstract function bombardstrength(); } class army extends unit { private $units = array(); function addunit( unit $unit ) { if ( in_array( $unit, $this->units, true ) ) { return; } $this->units[] = $unit; } function removeunit( unit $unit ) { // >= php 5.3 //$this->units = array_udiff( $this->units, array( $unit ), // function( $a, $b ) { return ($a === $b)?0:1; } ); // < php 5.3 $this->units = array_udiff( $this->units, array( $unit ), create_function( '$a,$b', 'return ($a === $b)?0:1;' ) ); } function bombardstrength() { $ret = 0; foreach( $this->units as $unit ) { $ret += $unit->bombardstrength(); } return $ret; } } class unitexception extends exception {} class archer extends unit { function addunit( unit $unit ) { throw new unitexception( get_class($this)." is a leaf" ); } function removeunit( unit $unit ) { throw new unitexception( get_class($this)." is a leaf" ); } function bombardstrength() { return 4; } } $archer = new archer(); $archer2 = new archer(); $archer->addunit( $archer2 ); ?>
output:
fatal error: uncaught exception 'unitexception' with message 'archer is a leaf'
点评:组合模式中的一切类都共享同一个父类型,可以轻松地在设计中添加新的组合对象或局部对象,而无需大范围地修改代码。
最终的效果,逐步优化(完美):
<?php class unitexception extends exception {} abstract class unit { abstract function bombardstrength(); function addunit( unit $unit ) { throw new unitexception( get_class($this)." is a leaf" ); } function removeunit( unit $unit ) { throw new unitexception( get_class($this)." is a leaf" ); } } class archer extends unit { function bombardstrength() { return 4; } } class lasercannonunit extends unit { function bombardstrength() { return 44; } } class army extends unit { private $units = array(); function addunit( unit $unit ) { if ( in_array( $unit, $this->units, true ) ) { return; } $this->units[] = $unit; } function removeunit( unit $unit ) { // >= php 5.3 //$this->units = array_udiff( $this->units, array( $unit ), // function( $a, $b ) { return ($a === $b)?0:1; } ); // < php 5.3 $this->units = array_udiff( $this->units, array( $unit ), create_function( '$a,$b', 'return ($a === $b)?0:1;' ) ); } function bombardstrength() { $ret = 0; foreach( $this->units as $unit ) { $ret += $unit->bombardstrength(); } return $ret; } } // create an army $main_army = new army(); // add some units $main_army->addunit( new archer() ); $main_army->addunit( new lasercannonunit() ); // create a new army $sub_army = new army(); // add some units $sub_army->addunit( new archer() ); $sub_army->addunit( new archer() ); $sub_army->addunit( new archer() ); // add the second army to the first $main_army->addunit( $sub_army ); // all the calculations handled behind the scenes print "attacking with strength: {$main_army->bombardstrength()}\n"; ?>
output:
attacking with strength: 60
更牛逼的组合处理,
<?php abstract class unit { function getcomposite() { return null; } abstract function bombardstrength(); } abstract class compositeunit extends unit { // 抽象类继承抽象类 private $units = array(); function getcomposite() { return $this; } protected function units() { return $this->units; } function removeunit( unit $unit ) { // >= php 5.3 //$this->units = array_udiff( $this->units, array( $unit ), // function( $a, $b ) { return ($a === $b)?0:1; } ); // < php 5.3 $this->units = array_udiff( $this->units, array( $unit ), create_function( '$a,$b', 'return ($a === $b)?0:1;' ) ); } function addunit( unit $unit ) { if ( in_array( $unit, $this->units, true ) ) { return; } $this->units[] = $unit; } } class army extends compositeunit { function bombardstrength() { $ret = 0; foreach( $this->units as $unit ) { $ret += $unit->bombardstrength(); } return $ret; } } class archer extends unit { function bombardstrength() { return 4; } } class lasercannonunit extends unit { function bombardstrength() { return 44; } } class unitscript { static function joinexisting( unit $newunit, unit $occupyingunit ) { // 静态方法,直接通过类名来使用 $comp; if ( ! is_null( $comp = $occupyingunit->getcomposite() ) ) { // 军队合并处理 $comp->addunit( $newunit ); } else { // 士兵合并处理 $comp = new army(); $comp->addunit( $occupyingunit ); $comp->addunit( $newunit ); } return $comp; } } $army1 = new army(); $army1->addunit( new archer() ); $army1->addunit( new archer() ); $army2 = new army(); $army2->addunit( new archer() ); $army2->addunit( new archer() ); $army2->addunit( new lasercannonunit() ); $composite = unitscript::joinexisting( $army2, $army1 ); print_r( $composite ); ?>
output:
army object ( [units:compositeunit:private] => array ( [0] => archer object ( ) [1] => archer object ( ) [2] => army object ( [units:compositeunit:private] => array ( [0] => archer object ( ) [1] => archer object ( ) [2] => lasercannonunit object ( ) ) ) ) )
点评:unit 基础,compositeunit复合中实现add与remove。军队继承composite,射手继承archer。这样射手中就不会有多余的add与remove方法了。
装饰模式
装饰模式帮助我们改变具体组件的功能。
看例子
<?php abstract class tile { // 砖瓦 abstract function getwealthfactor(); // 获取财富 } class plains extends tile { // 平原 private $wealthfactor = 2; function getwealthfactor() { return $this->wealthfactor; } } class diamondplains extends plains { // 钻石地段 function getwealthfactor() { return parent::getwealthfactor() + 2; } } class pollutedplains extends plains { // 污染地段 function getwealthfactor() { return parent::getwealthfactor() - 4; } } $tile = new pollutedplains(); print $tile->getwealthfactor(); ?>
output:
-2
点评:不具有灵活性,我们不能同时获得钻石与被污染的土地的资金情况。
装饰模式使用组合和委托而不是只使用继承来解决功能变化的问题。
看例子:
<?php abstract class tile { abstract function getwealthfactor(); } class plains extends tile { private $wealthfactor = 2; function getwealthfactor() { return $this->wealthfactor; } } abstract class tiledecorator extends tile { // 装饰 protected $tile; function __construct( tile $tile ) { $this->tile = $tile; } } class diamonddecorator extends tiledecorator { // 钻石装饰 function getwealthfactor() { return $this->tile->getwealthfactor()+2; } } class pollutiondecorator extends tiledecorator { // 污染装饰 function getwealthfactor() { return $this->tile->getwealthfactor()-4; } } $tile = new plains(); print $tile->getwealthfactor(); // 2 $tile = new diamonddecorator( new plains() ); print $tile->getwealthfactor(); // 4 $tile = new pollutiondecorator( new diamonddecorator( new plains() )); print $tile->getwealthfactor(); // 0 ?>
output:
2
4
0
点评:这个模型具有扩展性。我们不需要创建diamondpollutionplains对象就可以构建一个钻石被污染的对象。
一个更逼真的例子
<?php class requesthelper{} // 请求助手 abstract class processrequest { // 进程请求 abstract function process( requesthelper $req ); } class mainprocess extends processrequest { // 主进程 function process( requesthelper $req ) { print __class__.": doing something useful with request\n"; } } abstract class decorateprocess extends processrequest { // 装饰进程 protected $processrequest; function __construct( processrequest $pr ) { // 引用对象,委托 $this->processrequest = $pr; } } class logrequest extends decorateprocess { // 日志请求 function process( requesthelper $req ) { print __class__.": logging request\n"; // 当前类,有点递归的感觉 $this->processrequest->process( $req ); } } class authenticaterequest extends decorateprocess { // 认证请求 function process( requesthelper $req ) { print __class__.": authenticating request\n"; $this->processrequest->process( $req ); } } class structurerequest extends decorateprocess { // 组织结构请求 function process( requesthelper $req ) { print __class__.": structuring request\n"; $this->processrequest->process( $req ); } } $process = new authenticaterequest( new structurerequest( new logrequest ( new mainprocess() ))); // 这样可以很灵活的组合进程的关系,省去很多重复的继承 $process->process( new requesthelper() ); print_r($process); ?>
output:
authenticaterequest: authenticating request structurerequest: structuring request logrequest: logging request mainprocess: doing something useful with request authenticaterequest object ( [processrequest:protected] => structurerequest object ( [processrequest:protected] => logrequest object ( [processrequest:protected] => mainprocess object ( ) ) ) )
点评:这里有一种递归的感觉,一层调用一层。模式是牛人总结出来用于灵活的解决一些现实问题的。牛!给开发多一点思路。
更多关于php相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《php基本语法入门教程》、《php运算与运算符用法总结》、《php网络编程技巧总结》、《php数组(array)操作技巧大全》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家php程序设计有所帮助。