php装饰者模式

2021-03-24  本文已影响0人  一路向后

1.装饰者模式简介

   装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

2.源码实现

<?php

/*抽象构件*/
interface IComponent
{
    public function Display();
}

/*具体构件Person*/
class Person implements IComponent
{
    private $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function Display()
    {
        echo "装饰的: {$this->name}\n";
    }
}

/*抽象装饰器*/
class Clothes implements IComponent
{
    protected $component;

    public function Decorate(IComponent $component)
    {
        $this->component = $component;
    }

    public function Display()
    {
        if(!empty($this->component))
        {
            $this->component->Display();
        }
    }
}

/*具体装饰器: 皮鞋*/
class PiXie extends Clothes
{
    public function Display()
    {
        echo "皮鞋\n";
        parent::Display();
    }
}

$Yaoming = new Person("姚明");
$pixie = new PiXie();

//$pixie->Decorate($Yaoming);

$Yaoming->Display();

?>

3.运行及其结果

$ php example.php
装饰的: 姚明
上一篇 下一篇

猜你喜欢

热点阅读