news 2026/6/7 9:34:22

PHP设计模式组合与迭代器

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
PHP设计模式组合与迭代器

PHP设计模式组合与迭代器

组合模式和迭代器模式都是结构型设计模式。组合模式让客户端统一处理单个对象和组合对象,迭代器提供遍历集合的标准方式。今天说说这两种模式。

组合模式在树形结构中很有用。

```php
abstract class FileSystemComponent
{
protected string $name;
public function __construct(string $name) { $this->name = $name; }
abstract public function getSize(): int;
abstract public function display(int $depth = 0): void;
}

class File extends FileSystemComponent
{
private int $size;

public function __construct(string $name, int $size)
{
parent::__construct($name);
$this->size = $size;
}

public function getSize(): int { return $this->size; }

public function display(int $depth = 0): void
{
echo str_repeat(" ", $depth) . "📄 {$this->name} ({$this->size}KB)\n";
}
}

class Directory extends FileSystemComponent
{
private array $children = [];

public function add(FileSystemComponent $component): void
{
$this->children[] = $component;
}

public function getSize(): int
{
$total = 0;
foreach ($this->children as $child) $total += $child->getSize();
return $total;
}

public function display(int $depth = 0): void
{
echo str_repeat(" ", $depth) . "📁 {$this->name}/\n";
foreach ($this->children as $child) $child->display($depth + 1);
}
}

$root = new Directory("root");
$home = new Directory("home");
$home->add(new File("readme.txt", 10));
$home->add(new File("photo.jpg", 500));
$root->add($home);
$root->add(new File("config.php", 50));

$root->display();
echo "总大小: {$root->getSize()}KB\n";
?>

迭代器提供统一的遍历方式。

```php
class RangeIterator implements Iterator
{
private int $current;
private int $end;
private int $step;

public function __construct(int $start, int $end, int $step = 1)
{
$this->current = $start;
$this->end = $end;
$this->step = $step;
}

public function current(): mixed { return $this->current; }
public function key(): mixed { return $this->current; }

public function next(): void
{
$this->current += $this->step;
}

public function rewind(): void
{
$this->current = 0;
}

public function valid(): bool
{
return $this->current <= $this->end;
}
}

foreach (new RangeIterator(1, 5) as $num) {
echo "$num ";
}
echo "\n";
?>

组合模式让叶子节点和容器节点有统一的接口。迭代器让集合的遍历方式统一。两种模式在框架和库中广泛应用,PHP的SPL提供了多种迭代器实现。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/7 9:33:17

ATK GEAR游戏键盘选购导航:从入门到旗舰的精准指南

摘要 选择一款合适的磁轴键盘&#xff0c;关键在于明确你的游戏场景、预算和功能偏好。对于追求极致响应速度的FPS玩家&#xff0c;ATK GEAR的第三代烈风ULTRA自研方案提供了0.28ms超低延迟和0.001mm行程精度&#xff1b;对于需要兼顾学习和娱乐的大学生&#xff0c;其68键/75%…

作者头像 李华
网站建设 2026/6/7 9:28:03

Kubernetes 网络策略深度解析:从原理到生产落地实践

Kubernetes 网络策略深度解析&#xff1a;从原理到生产落地实践一、微服务集群的网络隔离困境&#xff1a;从一次故障谈起 在大规模微服务架构中&#xff0c;网络安全与访问控制是运维工作的重中之重。没有哪台服务器是一次重启解决不了的&#xff0c;如果有&#xff0c;那就是…

作者头像 李华
网站建设 2026/6/7 9:28:00

VB程序老崩溃?这套错误处理机制让我三年没出过事故

VB程序老崩溃&#xff1f;这套错误处理机制让我三年没出过事故 写VB的人分两种&#xff1a;一种是程序报错了才知道哪里出问题&#xff0c;另一种是程序还没崩就已经把异常兜住了。我以前属于第一种&#xff0c;做的库存管理系统上线第一天就崩了三次&#xff0c;客户打电话过来…

作者头像 李华