PHP设计模式组合与迭代器

PHP设计模式组合与迭代器 PHP设计模式组合与迭代器组合模式和迭代器模式都是结构型设计模式。组合模式让客户端统一处理单个对象和组合对象迭代器提供遍历集合的标准方式。今天说说这两种模式。组合模式在树形结构中很有用。phpabstract 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;?迭代器提供统一的遍历方式。phpclass 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提供了多种迭代器实现。