设计模式3.1-装饰者模式

<?php
/*
* 装饰者模式:动态地将责任附加到对象上
*
* 在装饰者模式中,装饰者和被装饰者继承自同一个类。装饰者会持有一个被装饰者的对象,在方法中通过在调用被装饰者相应方法的前后添加自己的逻辑,从而达到添加功能的目的。装饰者模式提供了一种类似于继承的另一种扩展方式
*
* 在此示例中,具体Human和HumanDecorator同属Human抽象类。装饰者会持有一个Human实例,在HumanDecorator调用display时会在调用Human的display方法的前后包装一层自己的逻辑,从而达到扩展功能的目的。
*
*
*/
abstract class Human
{
    abstract public function display();
}

class YellowHuman extends Human
{
    public function display()
    {
        echo "YellowHuman";
    }
}

class BlackHuman extends Human
{
    public function display()
    {
        echo "BlackHuman";
    }
}

abstract class HumanDecorator extends Human
{
    protected $human;
    public function __construct(Human $human)
    {
        $this->human = $human;
    }
}

class WatchDecorator extends HumanDecorator
{
    public function display()
    {
        echo $this->human->display()." with a Watch";
    }
}

class GlassesDecorator extends HumanDecorator
{
    public function display()
    {
        echo $this->human->display()." with a Glasses";
    }
}


class Test
{
    public function run()
    {
        $yellowHuman = new YellowHuman();
        $blackHuman = new BlackHuman();


        $yellowHumanWithWatch = new WatchDecorator($yellowHuman);
        $blackHumanWithGlasses = new GlassesDecorator($blackHuman);

        $yellowHumanWithWatchWithGlasses = new GlassesDecorator($yellowHumanWithWatch);

        $yellowHuman->display();
        echo "<br>\n";
        $blackHuman->display();
        echo "<br>\n";

        $yellowHumanWithWatch->display();
        echo "<br>\n";
        $blackHumanWithGlasses->display();
        echo "<br>\n";

        $yellowHumanWithWatchWithGlasses->display();
    }
}

$test = new Test();
$test->run();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值