php - EmptyIterator 的目的是什么?

标签 php iterator

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

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

No operation, nothing to do.

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

空迭代器的目标是什么?

最佳答案

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

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 Object Pattern Class,那么默认值将不得不做自己的事情并跳过下面的代码行。通过制作一个空对象,一切仍然可以很好地完成。当我们不希望任何事情发生时,我们只会让任何事情发生。

关于php - EmptyIterator 的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32762768/

相关文章:

php - 生成带有创建日期的文件名

scala - 使用 Scala 迭代器中的项目

c++ - 我要在队列前端访问时锁定互斥体吗

java - Java 8 中 Spliterator 的一个好的用例场景是什么?

c++ - boost 具有不同谓词的过滤器迭代器

c++ - 有没有办法为 std::map 中小于给定键的第一个元素找到反向迭代器?

php - 来自图像数组ffmpeg windows php的视频

PHP数组到SQL

PHP:在唯一页面中显示博客页面

php - CMS 中小部件的 MySQL 模式