组合模式
UML图
树形结构图
代码示例
abstract class Component
{
abstract public function add(Component $c);
abstract public function remove(Component $c);
abstract public function operation();
abstract public function getChild();
}
class Leaf extends Component
{
public function add(Component $c)
{
throw new \Exception('Leaf不能有子项');
}
public function remove(Component $c)
{
throw new \Exception('Leaf不能有子项');
}
public function operation()
{
return 1;
}
public function getChild()
{
throw new \Exception('Leaf不能有子项');
}
}
class Composite extends Component
{
protected $child=[];
public function add(Component $c)
{
array_push($this->child, $c);
}
public function remove(Component $c)
{
foreach ($this->child as $i=>$v) {
if ($v==$c) {
unset($this->child[$i]);
}
}
}
public function operation()
{
$sum=0;
foreach ($this->child as $v) {
$sum+=$v->operation();
}
return $sum;
}
public function getChild($index)
{
return $this->child($index);
}
}
实际例子
游戏技能伤害设计:
装饰模式
UML图
代码示例
abstract class Component
{
abstract public function method();
}
abstract class Decorator extends Component{
private Component component;
public __constrcut(Component component)
{
$this->component = component;
}
public sampleOperation() {
$this->component->sampleOperation();
}
}
class ConcreateComponent extends Component
{
public function method()
{
}
}
class ConcreateDecorator extends Component{
private Component component;
public method() {
$this->component->method();
}
}
组合模式和装饰模式的区别
- 组合模式类似树形结构,装饰模式类似串形结构
- 组合模式一个组件可以包含多个子组件,装饰模式一个装饰组件只能包含一个组件
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。