php设计模式--装饰模式(七)装饰模式完成文章编辑

简介: php设计模式--装饰模式(七)装饰模式完成文章编辑

装饰器模式decorator

1. 装饰器模式(Decorator ) ,可以动态地添加修改类的功能

2.一个类提供了一项功能,如果要在修改并添加额外的功能,传统

的编程模式,需要写一个子类继承它,并重新实现类的方法

3.使用装饰器模式,仅需在运行时添加一个装饰器对象即可实现

可以实现最大的灵活性

 

<?php
//装饰器模式做文章修饰功能
class BaseArt {
  protected $content;
  protected $art = null;
  public function __construct($content) { 
    $this->content = $content ;
  }
  public function decorator() {
    return $this->content;
  }
}
/*  
class BianArt extends BaseArt{
  public function decorator(){
   return parent::decorator()."小编加了摘要";
  }
}
  
class SEOArt extends BaseArt{
  public function decorator(){
   return parent::decorator()."SEO加了";
  }
}
//现在这两个是平级的没有了继承 也不知道先后顺序 怎么办?
  
$BA = new BaseArt('天天向上');
 $BA->decorator();
  
$art = new BianArt('art');
echo $art->decorator()  
*/
class BianArt extends BaseArt{
  public function __construct(BaseArt $art){
    //普通文章传过来 自己调用自己给加上内容
    $this->art=$art;
    $this->decorator();
  }
  public function decorator(){
   //return parent::decorator()."小编加了摘要";
  return $this->content= $this->art->decorator()."小编加了摘要";
  }
}
class SeoArt extends BaseArt{
  public function __construct(BaseArt $art){
    //普通文章传过来 自己调用自己给加上内容
    $this->art=$art;
    $this->decorator();
  }
  public function decorator(){   
  return $this->content= $this->art->decorator()."seo优化";
  }
}   
$con = new BianArt(new BaseArt('con'));
echo $con->decorator(); 
//呵呵接下来有意思了就是new中new
// new BianArt(new BaseArt)
$con2 = new SeoArt(new BianArt(new BaseArt('con')));
echo $con2->decorator();
?>

 

目录
相关文章
|
20天前
|
设计模式 算法 PHP
php设计模式--策略模式(六)
php设计模式--策略模式(六)
11 0
|
3月前
|
设计模式 中间件 PHP
设计模式 | 装饰模式
设计模式 | 装饰模式
15 0
|
5月前
|
设计模式
设计模式系列教程(12) - 装饰模式
设计模式系列教程(12) - 装饰模式
16 0
|
6月前
|
设计模式 算法 uml
结构型设计模式01-装饰模式
结构型设计模式01-装饰模式
15 0
|
20天前
|
设计模式 Java PHP
php设计模式--简单工厂模式(一)
php设计模式--简单工厂模式(一)
14 0
|
6天前
|
设计模式 Go
[设计模式 Go实现] 结构型~装饰模式
[设计模式 Go实现] 结构型~装饰模式
|
20天前
|
设计模式 PHP
php设计模式--责任链模式(五)
php设计模式--责任链模式(五)
13 0
|
4月前
|
设计模式 容器
设计模式之装饰模式(2)--有意思的想法
设计模式之装饰模式(2)--有意思的想法
|
4月前
|
设计模式
设计模式之装饰模式--优雅的增强
设计模式之装饰模式--优雅的增强
设计模式之装饰模式--优雅的增强