当前位置: 首页 > 编程文章 >

PHP面向对象程序设计组合模式与装饰模式详解

PHP面向对象程序设计组合模式与装饰模式详解

作者:江禾时间:2025-10-06 15:23:53浏览:331

本文详解PHP中的组合模式与装饰模式。组合模式通过单根继承体系让不同职责的集合协同工作,如军队整合成员输出火力,支持动态增删组件且无需大范围修改代码。装饰模式利用组合与委托替代单纯继承,灵活扩展对象功能,例如在不创建新类的情况下为钻石土地添加污染属性,实现递归式的功能叠加。

本文目录展开

本实例深入剖析了PHP面向对象编程中的组合模式与装饰模式,旨在提供实用的参考代码与分析思路。

组合模式的定义与应用

组合模式

该模式构建了一个单一的根继承结构,允许职责各异的组件集合在同一框架下协同运作。

以军事指挥系统为例,


<?php
abstract class Unit { // 个体
  abstract function bombardStrength();
}
class Archer extends Unit { // 弓箭手
  function bombardStrength() {
    return 4;
  }
}
class LaserCannonUnit extends Unit { // 火炮手
  function bombardStrength() {
    return 44;
  }
}
?>

军队作为整体整合下属单位,统一计算并输出总火力值。


<?php
abstract class Unit {
  abstract function bombardStrength();
}
class Archer extends Unit {
  function bombardStrength() {
    return 4;
  }
}
class LaserCannonUnit extends Unit {
  function bombardStrength() {
    return 44;
  }
}
class Army { // 军队
  private $units = array(); // 定义私有属性 个体集
  function addUnit( Unit $unit ) { // 添加成员
    array_push( $this->units, $unit );
  }
  function bombardStrength() { // 火力
    $ret = 0;
    foreach( $this->units as $unit ) {
      $ret += $unit->bombardStrength();
    }
    return $ret;
  }
}
$unit1 = new Archer();
$unit2 = new LaserCannonUnit();
$army = new Army();
$army->addUnit( $unit1 );
$army->addUnit( $unit2 );
print $army->bombardStrength(); // 输出火力
?>

执行结果如下: 48 随后军队进一步合并其他部队单位。


<?php
abstract class Unit {
  abstract function bombardStrength();
}
class Archer extends Unit {
  function bombardStrength() {
    return 4;
  }
}
class LaserCannonUnit extends Unit {
  function bombardStrength() {
    return 44;
  }
}
class Army {
  private $units = array();
  private $armies= array();
  function addUnit( Unit $unit ) {
    array_push( $this->units, $unit );
  }
  function addArmy( Army $army ) {
    array_push( $this->armies, $army );
  }
  function bombardStrength() {
    $ret = 0;
    foreach( $this->units as $unit ) {
      $ret += $unit->bombardStrength();
    }
    foreach( $this->armies as $army ) {
      $ret += $army->bombardStrength();
    }
    return $ret;
  }
}
$unit1 = new Archer();
$unit2 = new LaserCannonUnit();
$army = new Army();
$army->addUnit( $unit1 );
$army->addUnit( $unit2 );
print $army->bombardStrength();
print "\n";
$army2 = clone $army; // 克隆军队
$army->addArmy( $army2 );
print $army->bombardStrength();
print "\n";
?>

更新后的输出结果为: 48 96

采用更优的设计方案,能够支持新增或移除组件等扩展功能。


<?php
abstract class Unit {
  abstract function addUnit( Unit $unit );
  abstract function removeUnit( Unit $unit );
  abstract function bombardStrength();
}
class Army extends Unit { // 军队
  private $units = array();
  function addUnit( Unit $unit ) {
    if ( in_array( $unit, $this->units, true ) ) { // $this用于调用正常的属性或方法,self调用静态的方法,属性或者常量
      return;
    }
    $this->units[] = $unit;
  }
  function removeUnit( Unit $unit ) {
    // >= php 5.3
    $this->units = array_udiff( $this->units, array( $unit ),
            function( $a, $b ) { return ($a === $b)?0:1; } );
    // < php 5.3
    // $this->units = array_udiff( $this->units, array( $unit ),
    //        create_function( '$a,$b', 'return ($a === $b)?0:1;' ) );
    // 对象数组,create_function,创建函数
  }
  function bombardStrength() {
    $ret = 0;
    foreach( $this->units as $unit ) {
      $ret += $unit->bombardStrength();
    }
    return $ret;
  }
}
// quick example classes
class Tank extends Unit { // 坦克
  function addUnit( Unit $unit ) {}
  function removeUnit( Unit $unit ) {}
  function bombardStrength() {
    return 4;
  }
}
class Soldier extends Unit { // 士兵
  function addUnit( Unit $unit ) {}
  function removeUnit( Unit $unit ) {}
  function bombardStrength() {
    return 8;
  }
}
$tank = new Tank();
$tank2 = new Tank();
$soldier = new Soldier();
$army = new Army();
$army->addUnit( $soldier );
$army->addUnit( $tank );
$army->addUnit( $tank2 );
print_r( $army );
print $army->bombardStrength()."\n";
$army->removeUnit( $soldier );
print_r( $army );
print $army->bombardStrength()."\n";
?>

输出示例:


Army Object
(
  [units:Army:private] => Array
    (
      [0] => Soldier Object
        (
        )
      [1] => Tank Object
        (
        )
      [2] => Tank Object
        (
        )
    )
)
16
Army Object
(
  [units:Army:private] => Array
    (
      [1] => Tank Object
        (
        )
      [2] => Tank Object
        (
        )
    )
)
8

引入异常处理机制以增强健壮性。


<?php
abstract class Unit {
  abstract function addUnit( Unit $unit );
  abstract function removeUnit( Unit $unit );
  abstract function bombardStrength();
}
class Army extends Unit {
  private $units = array();
  function addUnit( Unit $unit ) {
    if ( in_array( $unit, $this->units, true ) ) {
      return;
    }
    $this->units[] = $unit;
  }
  function removeUnit( Unit $unit ) {
    // >= php 5.3
    //$this->units = array_udiff( $this->units, array( $unit ),
    //        function( $a, $b ) { return ($a === $b)?0:1; } );
    // < php 5.3
    $this->units = array_udiff( $this->units, array( $unit ),
            create_function( '$a,$b', 'return ($a === $b)?0:1;' ) );
  }
  function bombardStrength() {
    $ret = 0;
    foreach( $this->units as $unit ) {
      $ret += $unit->bombardStrength();
    }
    return $ret;
  }
}
class UnitException extends Exception {}
class Archer extends Unit {
  function addUnit( Unit $unit ) {
    throw new UnitException( get_class($this)." is a leaf" );
  }
  function removeUnit( Unit $unit ) {
    throw new UnitException( get_class($this)." is a leaf" );
  }
  function bombardStrength() {
    return 4;
  }
}
$archer = new Archer();
$archer2 = new Archer();
$archer->addUnit( $archer2 );
?>

运行输出:

Fatal error: Uncaught exception 'UnitException' with message 'Archer is a leaf'

分析指出,在组合模式中所有类均共享同一父类型,这使得在设计阶段轻松添加新的组合对象或叶子节点成为可能,而无需对现有代码进行大规模重构。

经过逐步优化后的最终完美效果如下:


<?php
class UnitException extends Exception {}
abstract class Unit {
  abstract function bombardStrength();
  function addUnit( Unit $unit ) {
    throw new UnitException( get_class($this)." is a leaf" );
  }
  function removeUnit( Unit $unit ) {
    throw new UnitException( get_class($this)." is a leaf" );
  }
}
class Archer extends Unit {
  function bombardStrength() {
    return 4;
  }
}
class LaserCannonUnit extends Unit {
  function bombardStrength() {
    return 44;
  }
}
class Army extends Unit {
  private $units = array();
  function addUnit( Unit $unit ) {
    if ( in_array( $unit, $this->units, true ) ) {
      return;
    }
    $this->units[] = $unit;
  }
  function removeUnit( Unit $unit ) {
    // >= php 5.3
    //$this->units = array_udiff( $this->units, array( $unit ),
    //        function( $a, $b ) { return ($a === $b)?0:1; } );
    // < php 5.3
    $this->units = array_udiff( $this->units, array( $unit ),
            create_function( '$a,$b', 'return ($a === $b)?0:1;' ) );
  }
  function bombardStrength() {
    $ret = 0;
    foreach( $this->units as $unit ) {
      $ret += $unit->bombardStrength();
    }
    return $ret;
  }
}
// create an army
$main_army = new Army();
// add some units
$main_army->addUnit( new Archer() );
$main_army->addUnit( new LaserCannonUnit() );
// create a new army
$sub_army = new Army();
// add some units
$sub_army->addUnit( new Archer() );
$sub_army->addUnit( new Archer() );
$sub_army->addUnit( new Archer() );
// add the second army to the first
$main_army->addUnit( $sub_army );
// all the calculations handled behind the scenes
print "attacking with strength: {$main_army->bombardStrength()}\n";
?>

输出显示:

attacking with strength: 60

展示更高级的组合处理逻辑,


<?php
abstract class Unit {
  function getComposite() {
    return null;
  }
  abstract function bombardStrength();
}
abstract class CompositeUnit extends Unit { // 抽象类继承抽象类
  private $units = array();
  function getComposite() {
    return $this;
  }
  protected function units() {
    return $this->units;
  }
  function removeUnit( Unit $unit ) {
    // >= php 5.3
    //$this->units = array_udiff( $this->units, array( $unit ),
    //        function( $a, $b ) { return ($a === $b)?0:1; } );
    // < php 5.3
    $this->units = array_udiff( $this->units, array( $unit ),
            create_function( '$a,$b', 'return ($a === $b)?0:1;' ) );
  }
  function addUnit( Unit $unit ) {
    if ( in_array( $unit, $this->units, true ) ) {
      return;
    }
    $this->units[] = $unit;
  }
}
class Army extends CompositeUnit {
  function bombardStrength() {
    $ret = 0;
    foreach( $this->units as $unit ) {
      $ret += $unit->bombardStrength();
    }
    return $ret;
  }
}
class Archer extends Unit {
  function bombardStrength() {
    return 4;
  }
}
class LaserCannonUnit extends Unit {
  function bombardStrength() {
    return 44;
  }
}
class UnitScript {
  static function joinExisting( Unit $newUnit,
                 Unit $occupyingUnit ) { // 静态方法,直接通过类名来使用
    $comp;
    if ( ! is_null( $comp = $occupyingUnit->getComposite() ) ) { // 军队合并处理
      $comp->addUnit( $newUnit );
    } else { // 士兵合并处理
      $comp = new Army();
      $comp->addUnit( $occupyingUnit );
      $comp->addUnit( $newUnit );
    }
    return $comp;
  }
}
$army1 = new Army();
$army1->addUnit( new Archer() );
$army1->addUnit( new Archer() );
$army2 = new Army();
$army2->addUnit( new Archer() );
$army2->addUnit( new Archer() );
$army2->addUnit( new LaserCannonUnit() );
$composite = UnitScript::joinExisting( $army2, $army1 );
print_r( $composite );
?>

输出结果:


Army Object
(
  [units:CompositeUnit:private] => Array
    (
      [0] => Archer Object
        (
        )
      [1] => Archer Object
        (
        )
      [2] => Army Object
        (
          [units:CompositeUnit:private] => Array
            (
              [0] => Archer Object
                (
                )
              [1] => Archer Object
                (
                )
              [2] => LaserCannonUnit Object
                (
                )
            )
        )
    )
)

点评:Unit作为基础类,CompositeUnit复合类中实现了add与remove方法。军队类继承自Composite,射手类继承自Archer。这种设计确保了射手类中不会包含多余的add与remove方法,从而保持接口纯净。

装饰模式的功能扩展原理

装饰模式

该模式旨在帮助开发者动态改变具体组件的功能行为。

通过以下示例进行观察,


<?php
abstract class Tile { // 砖瓦
  abstract function getWealthFactor(); // 获取财富
}
class Plains extends Tile { // 平原
  private $wealthfactor = 2;
  function getWealthFactor() {
    return $this->wealthfactor;
  }
}
class DiamondPlains extends Plains { // 钻石地段
  function getWealthFactor() {
    return parent::getWealthFactor() + 2;
  }
}
class PollutedPlains extends Plains { // 污染地段
  function getWealthFactor() {
    return parent::getWealthFactor() - 4;
  }
}
$tile = new PollutedPlains();
print $tile->getWealthFactor();
?>

输出结果: -2

评价:此方案缺乏灵活性,无法同时获取钻石与被污染土地的复合资金状况。

装饰模式通过组合和委托机制,而非仅依赖继承,来有效解决功能变更的问题。

参考以下示例代码:


<?php
abstract class Tile {
  abstract function getWealthFactor();
}
class Plains extends Tile {
  private $wealthfactor = 2;
  function getWealthFactor() {
    return $this->wealthfactor;
  }
}
abstract class TileDecorator extends Tile { // 装饰
  protected $tile;
  function __construct( Tile $tile ) {
    $this->tile = $tile;
  }
}
class DiamondDecorator extends TileDecorator { // 钻石装饰
  function getWealthFactor() {
    return $this->tile->getWealthFactor()+2;
  }
}
class PollutionDecorator extends TileDecorator { // 污染装饰
  function getWealthFactor() {
    return $this->tile->getWealthFactor()-4;
  }
}
$tile = new Plains();
print $tile->getWealthFactor(); // 2
$tile = new DiamondDecorator( new Plains() );
print $tile->getWealthFactor(); // 4
$tile = new PollutionDecorator(
       new DiamondDecorator( new Plains() ));
print $tile->getWealthFactor(); // 0
?>

输出结果: 2 4 0

评价:该模型具备良好的扩展性。无需专门创建DiamondPollutionPlains这样的特定对象,即可构建出被污染的钻石对象。

一个更贴近实际应用的案例


<?php
class RequestHelper{} // 请求助手
abstract class ProcessRequest { // 进程请求
  abstract function process( RequestHelper $req );
}
class MainProcess extends ProcessRequest { // 主进程
  function process( RequestHelper $req ) {
    print __CLASS__.": doing something useful with request\n";
  }
}
abstract class DecorateProcess extends ProcessRequest { // 装饰进程
  protected $processrequest;
  function __construct( ProcessRequest $pr ) { // 引用对象,委托
    $this->processrequest = $pr;
  }
}
class LogRequest extends DecorateProcess { // 日志请求
  function process( RequestHelper $req ) {
    print __CLASS__.": logging request\n"; // 当前类,有点递归的感觉
    $this->processrequest->process( $req );
  }
}
class AuthenticateRequest extends DecorateProcess { // 认证请求
  function process( RequestHelper $req ) {
    print __CLASS__.": authenticating request\n";
    $this->processrequest->process( $req );
  }
}
class StructureRequest extends DecorateProcess { // 组织结构请求
  function process( RequestHelper $req ) {
    print __CLASS__.": structuring request\n";
    $this->processrequest->process( $req );
  }
}
$process = new AuthenticateRequest( new StructureRequest(
                  new LogRequest (
                  new MainProcess()
                  ))); // 这样可以很灵活的组合进程的关系,省去很多重复的继承
$process->process( new RequestHelper() );
print_r($process);
?>

输出内容:


AuthenticateRequest: authenticating request
StructureRequest: structuring request
LogRequest: logging request
MainProcess: doing something useful with request
AuthenticateRequest Object
(
  [processrequest:protected] => StructureRequest Object
    (
      [processrequest:protected] => LogRequest Object
        (
          [processrequest:protected] => MainProcess Object
            (
            )
        )
    )
)

点评:此处呈现出一种递归调用的感觉,层层嵌套调用。设计模式是专家为解决现实复杂问题而总结出的智慧结晶,极具启发性,能为开发人员提供更多解题思路。

希望上述关于PHP程序设计的阐述能对大家有所帮助。

上一篇
PHP list() 函数赋值与数组解构示例

PHP的list()函数用于将数组中的值赋给一组变量,其顺序基于数组索引而非键名。当数组元素数量少于变量数量时,剩余变量会被赋值为NULL并触发Notice警告;若数组包含字符串数字键,list()会将其视为普通元素参与赋值。通过调整数组结构或变量顺序,可灵活实现数据的提取与重组。

下一篇
PHP类与反射API详解:验证、调用与元数据检查

本文介绍PHP中用于检查和操作类的内置函数及Reflection API。通过class_exists、get_class等函数可验证类存在性及对象类型;利用__call魔术方法实现动态方法调用并传递参数。Reflection API能深入剖析类结构,获取属性、方法及构造函数参数的详细信息,比var_dump提供更清晰的继承与方法来源视图。

相关文章

更多
PHP组合模式实现菜单层级结构示例

本文通过PHP代码实例展示组合模式(Composite Pattern)在处理对象树形结构时的应用。该模式允许将对象组合成树形结构以表示“部分-整体”的层次关系,使得用户对单个对象和组合对象的使用具有一致性。示例中构建了包含多级子菜单的菜单系统,并演示了如何统一遍历所有菜单项及其内容,输出结果展示了清晰的层级缩进效果。

2026.08.02 718
PHP组合模式实战:星际争霸地图管理案例解析

本文通过星际争霸地图管理的实例,详细解析PHP中的组合模式。该模式允许将对象组合成树形结构以表示部分-整体层次结构,使得用户对单个对象和组合对象的使用具有一致性。文章展示了如何通过抽象基类统一处理地图文件和地图包文件夹,简化了代码逻辑并提升了扩展性。

2025.12.29 203
PHP组合模式Composite Pattern优点与实现过程

组合模式是一种结构型设计模式,允许将对象组合成树形结构以表示“部分-整体”的层次关系。在PHP中,通过定义抽象组件、叶子节点和容器节点,客户端可以一致地处理单个对象和组合对象。该模式简化了客户端代码,提高了系统的灵活性与可扩展性,并降低了复杂对象结构的维护成本。

2025.09.09 127
PHP结构型模式之组合模式

组合模式是一种结构型设计模式,允许将对象组合成树形结构以表示“部分-整体”的层次关系。在PHP中,通过定义抽象组件、叶子节点和容器节点,客户端可以一致地处理单个对象和组合对象。该模式简化了代码逻辑,提升了系统的灵活性与可扩展性,便于管理复杂的对象结构并降低维护成本。

2026.07.29 119
Java设计模式-组合模式详解

组合模式(Composite Pattern)是一种结构型设计模式,它将对象组合成树形结构以表示“部分-整体”的层次结构。该模式使得用户对单个对象和组合对象的使用具有一致性,从而简化了复杂结构的处理逻辑。本文通过文件管理场景解析其核心概念,并结合Java代码演示如何利用组合模式实现多种折扣方案的统一管理与冲突解决。

2026.09.05 806
PHP访问者模式与组合模式的结合应用解析

本文通过PHP代码示例深入解析访问者模式与组合模式的结合使用。访问者模式允许在不修改元素类的前提下定义新操作,核心在于被访问者调用访问者并传递自身。文章展示了抽象基类Unit中accept方法的实现机制,即动态生成visit方法名并执行回调,同时结合组合模式管理对象结构,便于统一处理复杂对象树中的不同节点类型。

2026.07.16 345

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。