如何将for循环转换为生产者? [英] How to convert a for-loop into a producer?
问题描述
有一个 SynchronousProducer 接口,它支持两种操作:
There is a SynchronousProducer interface, that supports two operations:
public interface SynchronousProducer<ITEM> {
/**
* Produces the next item.
*
* @return produced item
*/
ITEM next();
/**
* Tells if there are more items available.
*
* @return true if there is more items, false otherwise
*/
boolean hasNext();
}
消费者询问生产者是否还有更多可用的物品,以及是否没有任何物品进入关闭顺序.
Consumer asks the producer if there are more items available and if none goes into a shutdown sequence.
现在解决此问题.
此刻,有一个 for循环循环充当生产者:
At the moment there is a for-loop cycle that acts as a producer:
for (ITEM item: items) {
consumer.consume(item);
}
任务是将控制代码转换为以下代码:
The task is to convert a controlling code into the following:
while (producer.hasNext()) {
consumer.consume(producer.next())
}
consumer.shutdown();
问题.给出了项:如何编写实现 SynchronousProducer 接口的生产者并复制上面显示的for循环逻辑?
The question. Given the items: how to write the producer implementing SynchronousProducer interface and duplicating the logic of the for-loop shown above?
推荐答案
如果 items
实现了 Iterable
,则可以像下面这样将其适应SynchronousProducer接口:
If items
implements Iterable
, you can adapt it to your SynchronousProducer interface like this:
class IterableProducer<T> implements SynchronousProducer<T> {
private Iterator<T> iterator;
public IterableProducer(Iterable<T> iterable) {
iterator = iterable.iterator();
}
@Override
public T next() {
return iterator.next();
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
}
这篇关于如何将for循环转换为生产者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!