一天一个设计模式(10)——装饰器模式

装饰器模式

  装饰器模式是为了向一个现有的对象添加新的功能,在不想继承该对象的情况下使用,以避免子类较多的情况。

实例

  天气热的时候我们家宝宝要出门玩可以不换衣服直接出门。现在天气凉了,我想要出门前先穿上衣服,回家就脱掉。

  首先创建一个孩子玩的接口

/**
 * Interface Child
 */
interface Child
{
    public function play();
}
Interface Child

  夏天的时候想出去玩直接就出门啦

class MyChild implements Child
{
    public function play()
    {
        echo 'Go out!';
    }
}
MyChild

  创建一个装饰器类

class Decorator implements Child
{

    public $decoratorChild;

    /**
     * Decorator constructor.
     * @param $child Child
     */
    function __construct($child)
    {
        $this->decoratorChild = $child;
    }

    public function play()
    {
        $this->decoratorChild->play();
    }
}
Decorator

  冬天出门要先穿衣服,回家要脱衣服。

class MyChildNew extends Decorator{

    public function first(){
        echo "Wear clothes.";
    }

    public function last(){
        echo "Undress.";
    }

    public function play()
    {
        $this->first();
        parent::play();
        $this->last();
    }

}
MyChildNew

  执行结果:

$child=new MyChildNew(new MyChild());
$child->play();

//Wear clothes.Go out!Undress.

本文来自博客园,作者:Bin_x,转载请注明原文链接:https://www.cnblogs.com/Bin-x/p/design10.html

原文地址:https://www.cnblogs.com/Bin-x/p/design10.html