1. 定义一个生成器接口:
package generator;
public interface Generator<T> {
T next();
}
2. 实现类,用于生成Fibonacci数列:
package generator;
public class Fibonacci implements Generator<Integer> {
private int count = 0;
private int fib(int n) {
if(n < 2) {
return 1;
}
return fib(n-1) + fib(n-2);
}
@Override
public Integer next() {
return fib(count++);
}
public static void main(String[] args) {
Fibonacci gen = new Fibonacci();
for(int i=0; i<18; i++) {
System.out.print(gen.next() + " ");
}
}
}
//output
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584
3. 适配器,增加Iterable能力:
package generator;
import java.util.Iterator;
public class IterableFibonacci implements Iterable<Integer> {
private Fibonacci f = new Fibonacci(); //组合或继承均可
private int count = 0;
public IterableFibonacci(int count) {
this.count = count;
}
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
@Override
public boolean hasNext() {
return count > 0;
}
@Override
public Integer next() {
count --;
return f.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("unsupported operate");
}
};
}
public static void main(String[] args) {
for(Integer i : new IterableFibonacci(18)) {
System.out.print(i + " ");
}
}
}
//output
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584