Thinking in Java(6)
1.1 Readable接口简单应用
如果一个类继承了readable接口并实现了read方法,我们就可以使用scanner类来进行操作。read方法返回小于0的数表示没有可以读取的,s.hasNext就会退出,简单示例如下。
import java.io.*;
import java.util.*;
import java.nio.CharBuffer;
public class RandomString implements Readable{
private static char[] str = "ABC".toCharArray();
private Random rand = new Random(47);
private int count = 0; //产生随机字符串的个数
public RandomString(int count) {
this.count = count;
}
//Readable需要实现read方法
@Override
public int read(CharBuffer arg0) {
// TODO Auto-generated method stub
count--;
if(count < 0) return -1; //返回-1 结束
for(int i=0; i<5; i++) {
arg0.append(str[rand.nextInt(str.length)]);
}
arg0.append(' ');
return 1;
}
public static void main(String[] args) {
Scanner s = new Scanner(new RandomString(4));
while(s.hasNext()) {
System.out.println(s.next());
}
}
}
1.2 使用适配器使用Readable接口
假设我们现在有一个random double的类如下
RandomDoubles.java
import java.io.*;
import java.util.*;
//可以产生随机double数据的类
public class RandomDoubles {
private static Random rand = new Random(47);
public double next() {
return rand.nextDouble();
}
public static void main(String[] args) {
RandomDoubles rd = new RandomDoubles();
for(int i=0; i<7; i++) {
System.out.println(rd.next());
}
}
}
适配器类
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.Scanner;
//适配器模式 使用Readable接口
public class AdaptedRandomDoubles extends RandomDoubles implements Readable {
private int count;
public AdaptedRandomDoubles(int count) {
this.count = count;
}
@Override
public int read(CharBuffer cb) {
// TODO Auto-generated method stub
count--;
if(count < 0) return -1;
String result = Double.toString(next()) + " ";
cb.append(result);
return result.length();
}
public static void main(String[] args) {
Scanner s = new Scanner(new AdaptedRandomDoubles(10));
while(s.hasNext()) {
System.out.println(s.next());
}
}
}