一組對象與該對象的單個實例的處理方式一致。php
<?php namespace DesignPatterns\Structural\Composite; interface RenderableInterface { public function render(): string; }
<?php namespace DesignPatterns\Structural\Composite; /** * 該組合內的節點必須派生於該組件契約。爲了構建成一個組件樹, * 此爲強制性操做。 */ class Form implements RenderableInterface { /** * @var RenderableInterface[] */ private $elements; /** * 遍歷全部元素,並對他們調用 render() 方法,而後返回表單的完整 * 的解析表達。 * * 從外部上看,咱們不會看到遍歷過程,該表單的操做過程與單一對 * 象實例同樣 * * @return string */ public function render(): string { $formCode = '<form>'; foreach ($this->elements as $element) { $formCode .= $element->render(); } $formCode .= '</form>'; return $formCode; } /** * @param RenderableInterface $element */ public function addElement(RenderableInterface $element) { $this->elements[] = $element; } }
<?php namespace DesignPatterns\Structural\Composite; class InputElement implements RenderableInterface { public function render(): string { return '<input type="text" />'; } }
<?php namespace DesignPatterns\Structural\Composite; class TextElement implements RenderableInterface { /** * @var string */ private $text; public function __construct(string $text) { $this->text = $text; } public function render(): string { return $this->text; } }
<?php namespace DesignPatterns\Structural\Composite\Tests; use DesignPatterns\Structural\Composite; use PHPUnit\Framework\TestCase; class CompositeTest extends TestCase { public function testRender() { $form = new Composite\Form(); $form->addElement(new Composite\TextElement('Email:')); $form->addElement(new Composite\InputElement()); $embed = new Composite\Form(); $embed->addElement(new Composite\TextElement('Password:')); $embed->addElement(new Composite\InputElement()); $form->addElement($embed); // 此代碼僅做示例。在實際場景中,如今的網頁瀏覽器根本不支持 // 多表單嵌套,牢記該點很是重要 $this->assertEquals( '<form>Email:<input type="text" /><form>Password:<input type="text" /></form></form>', $form->render() ); } }
PHP 互聯網架構師 50K 成長指南+行業問題解決總綱(持續更新)sql
面試10家公司,收穫9個offer,2020年PHP 面試問題shell
★若是喜歡個人文章,想與更多資深開發者一塊兒交流學習的話,獲取更多大廠面試相關技術諮詢和指導,歡迎加入咱們的羣啊,暗號:phpzh(羣號碼856460874)。設計模式
內容不錯的話但願你們支持鼓勵下點個贊/喜歡,歡迎一塊兒來交流;另外若是有什麼問題 建議 想看的內容能夠在評論提出