(2.2)适配器之对象适配器

概念:适配器不继承特殊类了,而是把”特殊类”改成写在成员变量,构造时赋值,只需改这一点即可

 

package com.yoodb;

public class Adapter implements Target{
	
	private Adaptee adaptee;
	
	@Override
	public void request() {
		// TODO Auto-generated method stub
		this.adaptee.specificRequest();
	}

	public Adapter(Adaptee adaptee) {
		super();
		this.adaptee = adaptee;
	}
	
}

 

对象适配器应用

InputStreamReader 将 InputStream 适配到 Reader;需要继承InputStream实现Reader。

①解释InputStreamReader :是字节流向字符流转换的桥梁

InputStream 读取字节流(类):

Reader读取字符流(接口)

②public class InputStreamReader extends Reader

构造函数:public InputStreamReader(InputStream in) //将字节流转换为字符流

读取:read(char[] cbuf, int offset, int length)    //这已经是按照字符读取了

public static void transReadNoBuf() throws IOException {
		/**
		 * 没有缓冲区,只能使用read()方法。
		 */
		//读取字节流
//		InputStream in = System.in;//读取键盘的输入。
		InputStream in = new FileInputStream("D:\\demo.txt");//读取文件的数据。
		//将字节流向字符流的转换。要启用从字节到字符的有效转换,可以提前从底层流读取更多的字节.
		InputStreamReader isr = new InputStreamReader(in);//读取
//		InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\demo.txt"));//综合到一句。
			
		char []cha = new char[1024];
		int len = isr.read(cha);
		System.out.println(new String(cha,0,len));
		isr.close();
 
	}

	

 

posted @ 2019-03-18 10:11  测试开发分享站  阅读(84)  评论(0编辑  收藏  举报