组合模式

UML图

1.png

树形结构图

2.png

代码示例

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);
    }
}

实际例子

游戏技能伤害设计:

3.png

装饰模式

UML图

4.png

代码示例

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();
    }
}

组合模式和装饰模式的区别

  1. 组合模式类似树形结构,装饰模式类似串形结构
  2. 组合模式一个组件可以包含多个子组件,装饰模式一个装饰组件只能包含一个组件

新数学习小组
13 声望3 粉丝

新数学习小组: