import java.util.Iterator;
import java.util.Random;
public class Test {
public static void main(String[] args) {
// ATester.test();
Tester.test();
}
}
interface Generator
T next();
}
class A { }
class a extends A{ }
class b extends A{ }
class c extends A{ }
class d extends A{ }
/*
思路:
Generator这个生成器,你可以给它指定size,当你通过迭代器
调用它的生成方法时,你就只能生成你指定的size个元素。
*/
class ATester implements Generator,Iterable {
private Class\[\] types = {a.class,b.class,c.class,d.class};
private int size;
);
public ATester() {
}
public ATester(int size) {
this.size = size;
}
@Override
public A next() {
try{
return (A)types\[rand.nextInt(types.length)\].newInstance();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}
@Override
public Iterator<A> iterator() {
return new Iterator<A>() {
int count = size;
@Override
public boolean hasNext() {
;
}
@Override
public A next() {
count--;
return ATester.this.next();
}
};
}
static void test() {
ATester g = new ATester();
; i < ; i++) {
System.out.println(g.next());
}
}
}
/*
负责生成斐波那契数列的生成器!
*/
class Fibonacci implements Generator
,ppre=;
;
@Override
public Integer next() {
int result;
i++;
) {
result=;
}else{
result=pre+ppre;
}
ppre = pre;
pre = result;
return result;
}
}
//这个方案计算量太多了
class Fibonacci2 implements Generator
;
private int fbi(int i) {
) {
;
}
)+fbi(i-);
}
@Override
public Integer next() {
return fbi(++count);
}
}
//编写一个适配器
class FibonacciAdaptor implements Iterable
private int size;
private Fibonacci fibonacci;
public FibonacciAdaptor(int size, Fibonacci fibonacci) {
this.size = size;
this.fibonacci = fibonacci;
}
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
//我的方案,感觉没有书中的优雅
//int i = 0;
@Override
public boolean hasNext() {
//return i<size;
;
}
@Override
public Integer next() {
//i++;
size--;
return fibonacci.next();
}
};
}
}
class Tester{
static void test() {
Fibonacci f = new Fibonacci();
;
) {
System.out.print(f.next()+" ");
i++;
}
System.out.println();
Fibonacci2 f2 = new Fibonacci2();
i = ;
) {
System.out.print(f2.next()+" ");
i++;
}
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章