[PHP] 组合模式-结构型设计模式

时间:2022-07-28
本文章向大家介绍[PHP] 组合模式-结构型设计模式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

以单个对象的方式来对待一组对象

有一个接口类,有一个需实现的方法,其他所有类都实现它,在一个组合类的实现方法中循环调用另外其他类的方法

有一个公共的接口类

interface Renderable
{
    public function render(): string;
}

组合类,也实现了接口

class Form implements Renderable
{
    private array $elements;
    public function render(): string
    {
        //组合类里面循环调用其他类的同名方法
        foreach ($this->elements as $element) {
            $element->render();
        }
    }
    public function addElement(Renderable $element)
    {
        $this->elements[] = $element;
    }
}

子项类,也实现了接口

class InputElement implements Renderable
{
    public function render(): string
    {
    }
}
class TextElement implements Renderable
{
    public function render(): string
    {
    }
}

使用的时候,像使用单一类一样使用组合类

$form = new Form();
$form->addElement(new TextElement());
$form->addElement(new InputElement());
$form->render();