php装饰者模式

php装饰者模式


 

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

示例:

A、B、C编辑同一篇文章。

class Article{
    protected $content;

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

class editor_A extends Article{
    public function __construct(Article $obj){
        $this->content = $obj->content . '<br/>' . '编辑A新写的内容';
    }

    public function decorator(){
        return $this->content;
    }
}

class editor_B extends Article{
    public function __construct(Article $obj){
        $this->content = $obj->content . '<br/>' . '编辑B新写的内容';
    }
    public function decorator(){
        return $this->content;
    }
}

class editor_C extends Article{
    public function __construct(Article $obj){
        $this->content = $obj->content . '<br/>' . '编辑C新写的内容';
    }
    public function decorator(){
        return $this->content;
    }
}

$artCls = new Article('你好');

//编辑A先秀修改,然后编辑B修改,然后编辑C修改
$a = new editor_A($artCls);
$b = new editor_B($a);
$c = new editor_C($b);
echo $c->decorator();

//编辑B先秀修改,然后编辑A修改
$b = new editor_B($artCls);
$a = new editor_A($b);
echo $a->decorator();

//重点是传递参数的地方,使用Article $obj传递上一个操作的对象,
//来实现对同一个对象进行连续操作

 

转载于:https://www.cnblogs.com/gyfluck/p/9681874.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值