【Java学习】泛型接口学习,java泛型接口
分享于 点击 36992 次 点评:177
【Java学习】泛型接口学习,java泛型接口
【Java学习】代理 —— 学习自《Thinking In Java》
上一篇说道泛型类和元组,
那么,我们也可以想象,其实接口也是可以“泛化”的。
经过学习Thinking那本书,受到一些启发,也参照例子写了一下自己的理解吧。
OK,例子是一个Fibonacci数列(前2个数之和)。
我们先定义一个 泛型接口:
interface Generator<T> {
T next();
}
这里,原书的例子比较好理解,是工厂模式(不知道工厂是什么?暂且先理解为生产某个类型的吧!)的一种。
然后,创建一个Fibonacci类,继承这个接口:
class Fibonacci implements Generator<Integer> {
private int count = 0;
private int getFibonacci(int n) {
if (n < 2)
return 1;
return getFibonacci(n - 2) + getFibonacci(n - 1);
}
@Override
public Integer next() {
return getFibonacci(count++);
}
}
这里,count属性就是当前第几个,
getFibonacci(int n)就是,告诉方法现在是第几个,然后返回值给你。
接口的next()方法,每次通过getFibonacci方法,返回一个Integer,
实现都很简单,就不多说了。
在main方法里也很简单,我们直接打印出来就好。
Fibonacci fibonacci = new Fibonacci();
for (int i = 0; i < 20; i++) {
System.out.print(fibonacci.next() + " ");
}
结果:1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
到这里,泛型接口的一个例子就完成了。
是不是觉得意犹未尽?
好,既然我们每次返回的都是Integer,为什么不能支持foreach呢?
答案是可以的!这里有很多实现方式。
书上也提到,可以直接修改上面Fibonacci类,让他继承Iterable接口,这就不说了。
下面粘上2种其他的思路,一种是书上也提到的适配器模式,另一种是组合,其实都是大同小异。
先适配器模式的吧:
class IterableFibonacci extends Fibonacci implements Iterable<Integer> {
private int n;
public IterableFibonacci(int count) {
n = count;
}
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
@Override
public boolean hasNext() {
return n > 0;
}
@Override
public Integer next() {
n--;
return IterableFibonacci.this.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
组合的:
class AssemblyFibonacci extends Fibonacci {
private int n;
public AssemblyFibonacci(int count) {
n = count;
}
public Iterable<Integer> getIterable() {
return new Iterable<Integer>() {
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
@Override
public boolean hasNext() {
return n > 0;
}
@Override
public Integer next() {
n--;
return AssemblyFibonacci.this.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
}
然后就是main方法:
public class TestGenerator {
public static void main(String[] args) {
// 非Iterable类
Fibonacci fibonacci = new Fibonacci();
for (int i = 0; i < 20; i++) {
System.out.print(fibonacci.next() + " ");
}
System.out.println();
// Iterable类 适配器
IterableFibonacci iterableFibonacci = new IterableFibonacci(20);
for (Integer integer : iterableFibonacci) {
System.out.print(integer + " ");
}
System.out.println();
// Iterable类 组合
AssemblyFibonacci assemblyFibonacci = new AssemblyFibonacci(20);
for (Integer integer : assemblyFibonacci.getIterable()) {
System.out.print(integer + " ");
}
}
}
大概就这样,自己的一些思考和理解吧。
有什么问题欢迎批评指出!谢谢!
相关文章
- 暂无相关文章
用户点评