组合模式

面向对象中,有一个原则是:  组合优于继承的原则

今天学习了组合模式,做一个小总结。

组合模式的应用场景:
把整体和局部的关系用树形结构表示,从而客户端能够把一个一个的局部对象和由局部对象组合的整体对象采用同样的方法来对待;

组合模式的应用实例:

<?php
/**
 *  单元抽象类
 *  author caoxin 2014.7.18
 */
abstract class Unit
{
    /**
     * 作战能力
     */
    abstract public  function bomboardStrength();
      
}



/**
 *  弓箭手 
 *  author caoxin 2014.7.18
 */
class Archer extends Unit 
{
    /**
     * 作战能力
     */
    public  function bomboardStrength(){
        return 4;
        
    }
      
}

/**
 *  大炮 
 *  author caoxin 2014.7.18
 */
class  LaserCanonUnit extends Unit 
{
    /**
     * 作战能力
     */
    public  function bomboardStrength(){
        return 40;
        
    }
      
}


/**
 * 军队
 * author caoxin 2014.7.18
 */

class Army
{
    /**
     * 存储作战单元的数组
     * @var array
     */
    private $_units = array();

    /**
     * 添加作战单元
     */
    public function addUnit(Unit $unit){
        array_push($this->_units,$unit);
        
    }

   /**
    * 综合的作战能力
    */
    public function bomboardStrength(){
        $strength = 0;
        if(!empty($this->_units)){
            foreach( $this -> _units as $unit){
                $strength += $unit ->bomboardStrength();
            }
        }
        return $strength ;
    }


    
}


$army = new Army();
$army -> addUnit(new Archer() );
$army -> addUnit( new LaserCanonUnit());
$strengths = $army ->bomboardStrength();
echo $strengths;

?>

组合模式的优点:
能够灵活的组合局部对象和整体对象之间的关心,对客户端来说,局部对象和整体对象的调用没有差别,使调用简单。

组合模式的缺点:
1)组合操作的成本很高,如果一个对象树中有很多子对象,可能一个简单的调用就可能使系统崩溃;
2)对象持久化的问题,组合模式是树形结构,不能很好地在关系数据库中保存数据,但是却非常适合用于xml持久化;

原文地址:https://www.cnblogs.com/mingaixin/p/3853637.html