PHP设计模式之装饰者模式代码实例

yipeiwu_com5年前PHP代码库

定义:

装饰者模式就是不修改原类代码和继承的情况下动态扩展类的功能。传统的编程模式都是子类继承父类实现方法重载,使用装饰器模式,只需添加一个新的装饰器对象,更加灵活,避免类数量和层次过多。

角色:

Component(被装饰对象基类)
ConcreteComponent(具体被装饰对象)
Decorator(装饰者基类)
ContreteDecorator(具体的装饰者类)

示例代码:

//被装饰者基类
interface Component
{
  public function operation();
}
 
//装饰者基类
abstract class Decorator implements Component
{
  protected $component;
 
  public function __construct(Component $component)
  {
    $this->component = $component;
  }
 
  public function operation()
  {
    $this->component->operation();
  }
}
 
//具体装饰者类
class ConcreteComponent implements Component
{
  public function operation()
  {
    echo 'do operation'.PHP_EOL;
  }
}
 
//具体装饰类A
class ConcreteDecoratorA extends Decorator {
  public function __construct(Component $component) {
    parent::__construct($component);
 
  }
 
  public function operation() {
    parent::operation();
    $this->addedOperationA();  // 新增加的操作
  }
 
  public function addedOperationA() {
    echo 'Add Operation A '.PHP_EOL;
  }
}
 
//具体装饰类B
class ConcreteDecoratorB extends Decorator {
  public function __construct(Component $component) {
    parent::__construct($component);
 
  }
 
  public function operation() {
    parent::operation();
    $this->addedOperationB();
  }
 
  public function addedOperationB() {
    echo 'Add Operation B '.PHP_EOL;
  }
}
 
 
class Client {
 
  public static function main() {
    /*
    do operation
    Add Operation A
    */
    $decoratorA = new ConcreteDecoratorA(new ConcreteComponent());
    $decoratorA->operation();
 
 
    /*
    do operation
    Add Operation A 
    Add Operation B 
    */
    $decoratorB = new ConcreteDecoratorB($decoratorA);
    $decoratorB->operation();
  }
 
}
 
Client::main();

相关文章

PHP中HTTP方式下的Gzip压缩传输方法举偶

Gzip压缩传输能更加有效节约带宽流量。他先把文本压缩为.gz然后传输给浏览器,最后由浏览器负责解压缩呈现给用户。 老版本的浏览器可能不能显示,但是现在大多数浏览器都能显示。 启用Gzi...

php实现singleton()单例模式实例

本文实例讲述了php实现singleton()单例模式的方法。分享给大家供大家参考。具体实现方法如下: common.php文件如下: 复制代码 代码如下:<?php&nb...

PHP实现算式验证码和汉字验证码实例

在PHP网站开发中,验证码可以有效地保护我们的表单不被恶意提交,但是如果不使用算式验证码或者汉字验证码,仅仅使用简单的字母或者数字验证码,这样的验证码方案真的安全吗? 大家知道简单数字或...

php中json_encode处理gbk与gb2312中文乱码问题的解决方法

本文讲述了php中json_encode处理gbk与gb2312中文乱码问题的解决方法,具体方法如下: 1.json_encode()中文在gbk/gb2312中对中文返回为null...

PHP下载远程文件到本地存储的方法

本文实例讲述了PHP下载远程文件到本地存储的方法。分享给大家供大家参考。具体实现方法如下: <?php function GrabImage($url,$filenam...