概念

装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。

这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

我们通过下面的实例来演示装饰器模式的用法。其中,我们将把一个形状装饰上不同的颜色,同时又不改变形状类。

 

优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。 缺点:多层装饰比较复杂。

 

示例

Shape.class.php(抽象接口)

 

<?php

namespace Decorator;

interface Shape
{
public function draw();
}

        Circle.class.php(圆形具体实现类)

<?php

namespace Decorator;

class Circle implements Shape
{
public function draw()
{
print_r("Shape: Circle" );
}
}

        Rectangle.class.php(长方形具体实现类)

<?php

namespace Decorator;

class Rectangle implements Shape
{
public function draw()
{
print_r("Shape: Rectangle");
}
}

        ShapeDecorator.class.php(形状装饰类 抽象父类)

<?php

namespace Decorator;

abstract class ShapeDecorator implements Shape
{
protected $decoratorShape;

public function __construct(Shape $shape)
{
$this->decoratorShape = $shape;
}

public function draw()
{
$this->decoratorShape->draw();
}
}

        RedShapeDecorator.class.php

<?php

namespace Decorator;

class RedShapeDecorator extends ShapeDecorator{

public function __construct(Shape $shape)
{
parent::__construct($shape);
}

public function draw()
{
$this->decoratorShape->draw();
$this->setRedColor($this->decoratorShape);
}

private function setRedColor(Shape $shape)
{
print_r("red");
}
}

        decorator.php(客户端类)

<?php

spl_autoload_register(function ($className){
$className = str_replace('\\','/',$className);
include $className.".class.php";
});

use Decorator\Circle;
use Decorator\RedShapeDecorator;

$circle = new Circle();

$redCircle = new RedShapeDecorator(new Circle());
$redCircle->draw();