设计模式之装饰器模式(PHP实现)

/**
 * 装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
 * 这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。
 * 我们通过下面的实例来演示装饰器模式的用法。其中,我们将把一个形状装饰上不同的颜色,同时又不改变形状类。
 * 优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
 * 缺点:多层装饰比较复杂。
 */

(1)Shape.class.php(抽象接口)

<?php

namespace Decorator;

interface Shape
{
    public function draw();
}

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

<?php

namespace Decorator;

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

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

<?php

namespace Decorator;

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

(4)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();
    }
}

(5)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");
    }
}

(6)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();

 

posted @ 2018-06-06 00:16  周起  阅读(3095)  评论(0编辑  收藏  举报