動態地爲類的實例添加功能php
Zend Framework: Zend_Form_Element 實例的裝飾者laravel
Web Service層:REST服務的JSON與XML裝飾器(固然,在此只能使用其中的一種)面試
<?php namespace DesignPatterns\Structural\Decorator; /** * 建立渲染接口。 * 這裏的裝飾方法 renderData() 返回的是字符串格式數據。 */ interface RenderableInterface { public function renderData(): string; }
<?php namespace DesignPatterns\Structural\Decorator; /** * 建立 Webservice 服務類實現 RenderableInterface。 * 該類將在後面爲裝飾者實現數據的輸入。 */ class Webservice implements RenderableInterface { /** * @var string */ private $data; /** * 傳入字符串格式數據。 */ public function __construct(string $data) { $this->data = $data; } /** * 實現 RenderableInterface 渲染接口中的 renderData() 方法。 * 返回傳入的數據。 */ public function renderData(): string { return $this->data; } }
<?php namespace DesignPatterns\Structural\Decorator; /** * 裝飾者必須實現渲染接口類 RenderableInterface 契約,這是該設計 * 模式的關鍵點。不然,這將不是一個裝飾者而只是一個自欺欺人的包 * 裝。 * * 建立抽象類 RendererDecorator (渲染器裝飾者)實現渲染接口。 */ abstract class RendererDecorator implements RenderableInterface { /** * @var RenderableInterface * 定義渲染接口變量。 */ protected $wrapped; /** * @param RenderableInterface $renderer * 傳入渲染接口類對象 $renderer。 */ public function __construct(RenderableInterface $renderer) { $this->wrapped = $renderer; } }
<?php namespace DesignPatterns\Structural\Decorator; /** * 建立 Xml 修飾者並繼承抽象類 RendererDecorator 。 */ class XmlRenderer extends RendererDecorator { /** * 對傳入的渲染接口對象進行處理,生成 DOM 數據文件。 */ public function renderData(): string { $doc = new \DOMDocument(); $data = $this->wrapped->renderData(); $doc->appendChild($doc->createElement('content', $data)); return $doc->saveXML(); } }
<?php namespace DesignPatterns\Structural\Decorator; /** * 建立 Json 修飾者並繼承抽象類 RendererDecorator 。 */ class JsonRenderer extends RendererDecorator { /** * 對傳入的渲染接口對象進行處理,生成 JSON 數據。 */ public function renderData(): string { return json_encode($this->wrapped->renderData()); } }
<?php namespace DesignPatterns\Structural\Decorator\Tests; use DesignPatterns\Structural\Decorator; use PHPUnit\Framework\TestCase; /** * 建立自動化測試單元 DecoratorTest 。 */ class DecoratorTest extends TestCase { /** * @var Decorator\Webservice */ private $service; /** * 傳入字符串 'foobar' 。 */ protected function setUp() { $this->service = new Decorator\Webservice('foobar'); } /** * 測試 JSON 裝飾者。 * 這裏的 assertEquals 是爲了判斷返回的結果是否符合預期。 */ public function testJsonDecorator() { $service = new Decorator\JsonRenderer($this->service); $this->assertEquals('"foobar"', $service->renderData()); } /** * 測試 Xml 裝飾者。 */ public function testXmlDecorator() { $service = new Decorator\XmlRenderer($this->service); $this->assertXmlStringEqualsXmlString('<?xml version="1.0"?><content>foobar</content>', $service->renderData()); } }
PHP 互聯網架構師成長之路*「設計模式」終極指南shell
PHP 互聯網架構師 50K 成長指南+行業問題解決總綱(持續更新)json
面試10家公司,收穫9個offer,2020年PHP 面試問題設計模式
★若是喜歡個人文章,想與更多資深開發者一塊兒交流學習的話,獲取更多大廠面試相關技術諮詢和指導,歡迎加入咱們的羣啊,暗號:phpzh(君羊號碼856460874)。服務器
內容不錯的話但願你們支持鼓勵下點個贊/喜歡,歡迎一塊兒來交流;另外若是有什麼問題 建議 想看的內容能夠在評論提出併發