php设计模式(组合模式2)
来源:互联网 发布:淘宝卡首页搜索技术 编辑:程序博客网 时间:2024/06/07 03:12
//组合模式改进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
- php设计模式(组合模式2)
- php 设计模式(组合模式一)
- PHP设计模式系列(十四):组合模式
- [PHP设计模式]Composite(组合)模式范例
- 设计模式php实例:组合模式
- PHP设计模式之组合模式
- [php] 设计模式之 组合模式
- PHP设计模式——组合模式
- PHP:设计模式之组合模式
- PHP设计模式之组合模式
- 设计模式(2) ------------组合模式
- 组合设计模式2
- 设计模式:组合模式
- 设计模式-----组合模式
- 设计模式 组合模式
- 设计模式--组合模式
- 设计模式---组合模式
- 【设计模式】组合模式
- Linux(centos)的入门课程I(视频)
- 全民飞机大战Java
- Android开发中第三方炫酷的控件
- php 设计模式(组合模式一)
- 二十三、解释器模式——设计模式学习笔记
- php设计模式(组合模式2)
- POJ 3685 Matrix 二分求解第K大
- 各种分布式文件系统简介
- Excel的自动计算提示功能
- 后缀表达式
- Python学习(1)
- bzoj4922 Karp-de-Chant Number 动态规划+贪心
- 阿里巴巴2018校招笔试题
- Manacher算法