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 强制下载文件实现代码

复制代码 代码如下:<?php $file = 'monkey.gif'; if (file_exists($file)) {     header(...

php获取网页标题和内容函数(不包含html标签)

复制代码 代码如下:function getPageContent($url) {         &nb...

PHP之autoload运行机制实例分析

本文较为深入的分析了PHP的autoload运行机制。对于深入理解PHP运行原理有一定的帮助作用。具体分析如下: php实现autoload有两种方法: 1、拦截器__autoload(...

PHP迭代器接口Iterator用法分析

本文实例讲述了PHP迭代器接口Iterator用法。分享给大家供大家参考,具体如下: PHP Iterator接口的作用是允许对象以自己的方式迭代内部的数据,从而使它可以被循环访问,It...

PHP+redis实现微博的拉模型案例详解

本文实例讲述了PHP+redis实现微博的拉模型。分享给大家供大家参考,具体如下: 上回写了一篇推模型的内容,这回分享一篇拉模型的内容。 拉模型 拉模型就是展示微博的时候,获取自己的所有...