EmptyIterator的目的是什么?

时间:2015-09-24 13:33:32

标签: php iterator

在PHP手册中,有一个名为EmptyIterator的类

手册中提到了EmptyIterator::rewind()方法:

  

无操作,无事可做。

此类的其他方法抛出异常或返回false

空迭代器的目标是什么?

1 个答案:

答案 0 :(得分:4)

这是一个空对象模式类。它用于实际上什么都不做,并实现一个接口,就像该接口的其他对象一样。从长远来看,它使编码更容易。换句话说,因为它不是抽象的,我们可以从中创建一个对象,并将其方法用作该接口的另一个实现类。示例(不是我自己的代码,顺便说一句):

interface Animal {
    public function makeSound();
}

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

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'

如果没有Null对象模式类,则默认情况下必须执行自己的操作并跳过以下代码行。通过制作一个空对象,一切都可以完成。当我们不想发生任何事情时,我们将不会发生任何事情。

相关问题