Home > Backend Development > PHP Tutorial > PHP设计模式之组合模式

PHP设计模式之组合模式

WBOY
Release: 2016-06-23 13:03:17
Original
906 people have browsed it

组合模式属于结构型模式

概述:将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

组合和聚合都描述一个类长期持有其他类的一个或多个实例的情况。

聚合:被包含对象是容器的核心部分,但是他们也可以被其他对象所包含。聚合关系用一条以空心菱形开头的线来说明。

组合:被包含的对象只能被它的容器所引用。当容器被删除时,它也应该被删除。组合关系的菱形是实心的

/**

* 执行单元

*/

abstract class Unit{

public function bombardStrength();

}

/**

* 弓箭手

*/

class ArcherUnit extends Unit{

public function bombardStrength(){

return 4;

}

}

/**

* 激光大炮

*/

class LaserCannonUnit extends Unit{

public function bombardStrength(){

return 10;

}

}

/**

* 军队

*/

class Arm{

private $units = array();

private $strength = 0;

public function addUnit(Unit $unit){

array_push($this->units, $unit);

}

public function bombardStrength(){

foreach ($this->units as $unit){

$this->strength += $unit->bombardStrength();

}

}

}

/**

* 组合模式

*/

public function actionCombine(){

$archer = new ArcherUnit;

$laserCannon = new LaserCannonUnit;

$arm = new Arm;

$arm->addUnit($archer);

$arm->addUnit($laserCannon);

echo $arm->bombardStrength();

}

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template