php设计模式(组合模式2)

//组合模式改进
abstract class Unit{
    function getComposite(){
        return null;
    }
    abstract function bombardStrength();
}
abstract class CompositeUnit extends Unit{
    protected $units = array();
    public function getComposite(){
        return $this;
    }
    protected function units(){
        return $this->units;
    }
    public function removeUnit(Unit $unit){
        $this->units = array_udiff($this->units,array($unit),function($a, $b){
            if ($a===$b)
            {
                return 0;
            }
            return ($a>$b)?1:-1;
        });
    }
    public function addUnit( Unit $unit){
        if(in_array($unit, $this->units, true)){
            return;
        }
        $this->units[] = $unit;
    }
    public function bombardStrength()
    {
        $ret = 0;
        foreach($this->units as $unit){
            $ret += $unit->bombardStrength();
        }
        return $ret;
    }
}
//添加类这个类必须继承自composite;因为聚合工具类中要用到
class Army extends CompositeUnit{
    //public $units = [];

    public function bombardStrength()
    {
        $ret = 0;
        foreach($this->units as $unit){
            $ret += $unit->bombardStrength();
        }
        return $ret;
    }
}
//聚合工具类
class UnitScript{
    //代码解读  如果$occupyingUnit是抽象CompositeUnit的子类直接调用add
    static function joinExisting(Unit $unitNew, Unit $occupyingUnit ){
        $comm;
        if(!is_null($comm = $occupyingUnit->getComposite())){
            $comm->addUnit($unitNew);
        }else{
            //如果是unit的直接子类就实例化army;
            $comm = new Army();
            $comm->addUnit($unitNew);
            $comm->addUnit($occupyingUnit);
        }
        return $comm;
    }
}
//被聚合对象
class B extends Unit{
    function bombardStrength(){
        return 2;
    }
}
//被聚合对象
class A extends Unit{
    function bombardStrength(){
        return 2;
    }
}
//如果穿进去的对象都是unit的子类,则需要实现army类,
echo UnitScript::joinExisting(new B, new A)->bombardStrength();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值