组合模式和装饰模式

组合模式

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

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

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理