Java的IO中用到了适配器模式与装饰模式,首先我们来看看关于这两种模式的定义。
适配器模式:将一个类的接口,转换成客户期望的另外一个接口。适配器让原本接口不兼容的类可以合作无间。
装饰模式:动态的将责任附加到对象上。若要扩展此功能,装饰者提供了比继承更有弹性的替代方案。
具体来说:
1、在字符流Reader/Writer的使用中,InputStreamReader/OutputStreamWriter是作为适配器的存在。
2、而在字节流InputStream/OutputStream的使用中,FilterInputStream/FilterOutputStream是作为装饰器的存在。
首先看适配器模式:
public class ReaderTest {
public static void main(String[] args){
try (InputStream in = ReaderTest.class.getResourceAsStream("file.txt")//这里的InputStream就是被适配接口(源角色)
){
Reader reader = new InputStreamReader(in);//Reader是目标接口,InputStreamReader是适配器
char[] chars = new char[1024];
reader.read(chars);
System.out.println(new String(chars));
} catch (IOException e) {
e.printStackTrace();
}
//对象适配器模式充满着良好的OO设计原则:使用对象组合,以修改的接口包装被适配者,被适配者的任何子类,都可以搭配着适配器使用
}
}
然后是装饰模式:
抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
具体构件(ConcreteComponent)角色:定义一个将要接收附加责任的类。
装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。
具体装饰(ConcreteDecorator)角色:负责给构件对象“贴上”附加的责任。
public class InputTest {
public static void main(String[] args){
int c;
try (
//InputStream类是抽象组件,
//FileInputStream是具体组件,
//FilterInputStream是装饰器角色,
//BufferedInputStream是具体装饰器角色
InputStream in = new BufferedInputStream(InputTest.class.getResourceAsStream("test.txt"));
){
// while((c = in.read()) > 0){
// System.out.print((char)c);
// }
byte[] bytes = new byte[in.available()];
String s = new String(bytes, 0 , in.read(bytes));
System.out.println(s);
}catch (IOException e){
e.printStackTrace();
}
}
}