07
02月
2020
装饰器模式
模式定义
装饰器模式允许向一个现有的对象添加新的功能,同时又不改变其结构。
装饰器模式的优势
装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
装饰器模式的缺陷
多层装饰比较复杂。
代码示例
Decorator\Shape.class.php
<?php
namespace Decorator;
interface Shape
{
public function draw();
}Decorator\Circle.class.php
<?php
namespace Decorator;
class Circle implements Shape
{
public function draw()
{
echo "draw Circle" . "\n";
}
}Decorator\Rectangle.class.php
<?php
namespace Decorator;
class Rectangle implements Shape
{
public function draw()
{
echo "draw rectangle";
}
}Decorator\ShapeDecorator.class.php
<?php
namespace Decorator;
abstract class ShapeDecorator implements Shape
{
protected $decoratorShape;
public function __construct($shape)
{
$this->decoratorShape = $shape;
}
}Decorator\RedShape.class.php
<?php
namespace Decorator;
class RedShape extends ShapeDecorator
{
public function draw()
{
$this->decoratorShape->draw();
$this->setRedColor();
}
private function setRedColor(){
echo "color is red" . "\n";
}
}Decorator\DecoratorTest.php
<?php
spl_autoload_register(function ($className){
$className = str_replace("\\", "/", $className);
include $className . ".class.php";
});
use Decorator\Circle;
use Decorator\RedShape;
$circle = new Circle();
$circle->draw();
$redCircle = new RedShape($circle);
$redCircle->draw();测试示例:
php Decorator/DecoratorTest.php 输出: draw Circle draw Circle color is red
总结
装饰器模式的本质就是动态组合。这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。
代码地址:https://github.com/798256478/design-patterns/tree/master/Decorator