【设计模式】迭代器模式

行为型设计模式: 迭代器模式 iterator

提供一种方法顺序访问一个聚合对象中的各个元素, 而又不需要暴露该对象的内部表示.

PHP 标准库 (SPL) 定义了一个最适合此模式的接口迭代器!往往也需要实现 Countable 接口,允许在迭代器对象上使用 count($object) 方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
interface Aggregate
{
public function CreateIterator();
}

class ConcreteAggregate implements Aggregate
{
public function CreateIterator()
{
$list = [
"a",
"b",
"c",
"d",
];
return new ConcreteIterator($list);
}
}

interface MyIterator
{
public function First();
public function Next();
public function IsDone();
public function CurrentItem();
}

class ConcreteIterator implements MyIterator
{
private $list;
private $index;
public function __construct($list)
{
$this->list = $list;
$this->index = 0;
}
public function First()
{
$this->index = 0;
}

public function Next()
{
$this->index++;
}

public function IsDone()
{
return $this->index >= count($this->list);
}

public function CurrentItem()
{
return $this->list[$this->index];
}
}

$agreegate = new ConcreteAggregate();
$iterator = $agreegate->CreateIterator();

while (!$iterator->IsDone()) {
echo $iterator->CurrentItem(), PHP_EOL;
$iterator->Next();
}

可以在 Subject 里仅注重其本身的业务逻辑, 对于观察者模式下对观察者的notify 操作改为 implement 一个接口来实现, 使其 observable ?

SPL扩展实现观察者模式-完整源码:
https://github.com/zhangyue0503/designpatterns-php/blob/master/06.observer/source/spl_observer.php