适配器模式:
将一个类的接口转换成客户希望的另一个接口。使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
java例子:
下面是java中I/O使用的例子
public class InputStreamReader extends Reader {
private final StreamDecoder sd;
public InputStreamReader(InputStream in) {
super(in);
try {
sd = StreamDecoder.forInputStreamReader(in, this, (String)null);
} catch (UnsupportedEncodingException e) {
throw new Error(e);
}
}
public int read() throws IOException {
return sd.read();
}
......
}
总结:
- InputStreamReader 实现了Reader接口,并且持有了InputStream 的引用,这里是通过StreamDecoder 类间接持有的,因为byte到char要经过编码。
- 适配器就是InputStreamReader 类,源角色就是InputStream代表的实例对象,目标接口就是Reader类。
- 在I/O类库中还有很多类似的用法,如OutputStreamWriter、StringReader等