装饰器模式:顾名思义,就是将需要修改的对象进行修饰。
应用场景:比如文章的修饰功能,不同部门对同一个文件修改的地方不一样;帖子的发布;
//基础类;//这是已经写好的文章基础类装饰器方法,返回文章即可;
class BasisArtical
{
public function __construct($content = '')
{
$this->content = $content;
}
public function decoractor()
{
return $this->content;
}
}
//编辑部加产品; //编辑装饰器:将基础类的对象传进来,实现基础类的装饰器方法,并在自己的装饰器方法中加入自己的内容;
class EditArtical extends BasisArtical
{
private $artObj;
public function __construct(BasisArtical $art)
{
$this->artObj = $art;
}
public function decoractor()
{
return $this->content = $this->artObj->decoractor().'小编添加';
}
}
//产品部添加产品;
class ProductArtical extends BasisArtical
{
private $artObj;
public function __construct(BasisArtical $art)
{
$this->artObj = $art;
}
public function decoractor()
{
return $this->content = $this->artObj->decoractor().'产品经理添加';
}
}
$basicImplements = new BasisArtical('不负青春,不负卿');
echo $basicImplements->decoractor();
$editImplements = new EditArtical($basicImplements); //小编装饰器;
echo $editImplements->decoractor();
$productImplements = new productArtical($basicImplements); //产品装饰器;
echo $productImplements->decoractor();
PHP设计模式之装饰器模式
最新推荐文章于 2022-11-02 02:37:43 发布