//组合模式改进
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();
转载请注明原文地址: https://www.6miu.com/read-12196.html