"我们可以在任何现有类之上添加新的接口,所以这意味着让方法接受接口类型,是一种让任何类都可以对该方法进行适配的方式。"

demo:

有一个未实现Readable的类,让Scanner作用于它

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() + " ");
        }
    }
}
public class AdaptedRandomDoubles extends RandomDoubles implements Readable {
    
    private int count;
    public AdaptedRandomDoubles(int count){
        this.count = count;
    }
    
    @Override
    public int read(CharBuffer cb) throws IOException {
        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(7));
        while(s.hasNextDouble()){
            System.out.println(s.nextDouble() + " ");
        }
    }

}

 

posted on 2017-01-22 15:40  文森博客  阅读(154)  评论(0编辑  收藏  举报