【问题标题】:what is the purpose of EmptyIterator?EmptyIterator 的目的是什么?
【发布时间】:2015-09-24 13:33:32
【问题描述】:

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

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

无操作,无所事事。

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

空迭代器的目标是什么?

【问题讨论】:

    标签: php iterator


    【解决方案1】:

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

    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'
    

    如果没有空对象模式类,那么默认值将不得不做自己的事情并跳过以下代码行。通过制作一个空对象,一切仍然可以做得很好。当我们不希望发生任何事情时,我们只会什么都不发生。

    【讨论】:

    • 那么在那个例子中 rewind() 是在哪里被调用的
    • 我认为这个类可以和InfiniteIterator一起使用,生成一个无限循环。
    • 您能否展示您的代码示例,说明您究竟想要做什么,或者您只是想知道空对象模式是什么?
    • 它可以与递归循环结合使用。让一个倒带调用一个倒带,它调用一个倒带,依此类推,直到它调用一个不做任何事情的倒带。
    猜你喜欢
    • 2011-03-05
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 2018-11-04
    • 2015-01-17
    • 2021-11-05
    • 2011-09-26
    相关资源
    最近更新 更多