EmptyIterator并不是废材

PHP PSL标准库提供了一套很是实用的迭代器,ArrayIterator用以迭代数组,CachingIterator迭代缓存,DirectoryIterator迭代目录…,各类迭代器各有所用。但仔细看下来居然还有一个EmptyIterator。根据设计说明,The EmptyIterator class for an empty iterator. 它就是用来作空迭代的。设计模式

这真让人感到有点费解,空迭代的意义何在?数组

答案在这里,它就是用来放在须要空迭代的场合。在stackoverflow中,举了一个很恰当的例子:缓存

interface Animal {
    public function makeSound();
} 设计

class Dog implements Animal {
    public function makeSound() {
        echo "WOOF!";
    }
} code

class Cat implements Animal {
    public function makeSound() {
        echo "MEOW!";
    }
} 对象

class NullAnimal implements Animal { // Null Object Pattern Class
    public function makeSound() {
    }
} 继承

$animalType = 'donkey';
$animal; 接口

switch($animalType) {
    case 'dog' :
        $animal = new Dog();
        break;
    case 'cat' :
        $animal = new Cat();
        break;
    default :
        $animal = new NullAnimal();
}
$animal->makeSound(); // won't make any sound bcz animal is 'donkey'get

在上例中,当animal的类型不为列举的任何一个时,它提供一个“不产生任何声音”的NullAnimal对象,它使不管animal type是什么,animal老是属于Animal类的一种。这就让$animal有了归属的意义(老是属于Animal的类型)。input

在迭代器当中,你能够遍历的范围限定在[DirectoryIterator,FilesystemIterator,…],当提供的类型指示不在限制范围以内时,你能够强制返回一个EmptyIterator,这样,后续的操做就没必要将不合格的类型做错误或异常处理,这样作的好处是使操做产生连贯性,而不会中断。

这个策略在设计模式中常用。

$inputType = 'some';
switch ($inputType) {
case 'file':
$iterate = new FilesystemIterator(__FILE__);
break;
case 'dir':
$iterate = new DirectoryIterator(__DIR__);
break;
default:
$iterate = new EmptyIterator();
}
do {
// do some codes
} while ($iterate->valid());
// or
for ($iterate->rewind(); $iterate->valid(); $iterate->next()) {
$key = $iterate->key();
$current = $iterate->current();
    // other codes
}
EmptyIterator继承自Iterator接口,提供了迭代器的一些判断方法,使得它能够像其它迭代器同样遍历操做,除了返回为空或false。
注意,由于是空,因此尝试对EmptyIterator操做current或next方法会抛出Exception。
若是打算这么作,最好使用try…catch…接收异常处理。
相关文章
相关标签/搜索