PHP 设计模式之装饰器模式

xiaoxiao2021-02-28  111

装饰器模式,使得在一个类不能完全满足需求时对其进行一些特定的自定义处理,而无需要新创建一个类

<?php // 可以动态的添加修改类的功能 class Canvas { public function init() { echo "init"; } public function rect($top, $right, $bottom, $left) { echo $top, $right, $bottom, $left; } } // 目标,为 rect 方法增加一个输出标题 /** 传统方法 class Canvas2 extends Canvas { public function rect($top, $right, $bottom, $left) { echo "++++", $top, $right, $bottom, $left; } } $canvas = new Canvas2(); $canvas->init(); $canvas->rect(3,5,6,7); */ // 装饰器模式 class Danvas implements IDrawDecorator { private $decorators; public function init() { echo "init"; } public function rect($top, $right, $bottom, $left) { $this->beforeDraw(); echo $top, $right, $bottom, $left; $this->afterDraw(); } public function beforeDraw() { $decorators = array_reverse($this->decorators); foreach ($decorators as $decorator) { $decorator->beforeDraw(); } } public function afterDraw() { foreach ($this->decorators as $decorator) { $decorator->afterDraw(); } } public function addDecorator(IDrawDecorator $decorator) { $this->decorators[] = $decorator; } } interface IDrawDecorator { public function beforeDraw(); public function afterDraw(); } abstract class ADrawDecorator { public abstract function beforeDraw(); public abstract function afterDraw(); } class ColorDrawDecorator extends ADrawDecorator { public function beforeDraw() { echo "color before \n"; } } class SizeDrawDecorator extends ADrawDecorator { public function beforeDraw() { echo "size before \n"; } public function afterDraw() { echo "size after \n"; } } $canvas = new Danvas; $canvas->init(); $canvas->addDecorator(new ColorDrawDecorator); $canvas->addDecorator(new SizeDrawDecorator); $canvas->rect(4,6,7,8);
转载请注明原文地址: https://www.6miu.com/read-85797.html

最新回复(0)