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…接收異常處理。
相關文章
相關標籤/搜索