Java SDK中的装饰器模式InputStream和OutputStream
装饰器模式是一种结构型设计模式,它可以在不改变现有对象的基础上动态地添加功能。Java SDK中的InputStream和OutputStream就是使用了装饰器模式。
InputStream和OutputStream是抽象类,它们提供了对I/O操作的基本支持。装饰器模式通过在基本的输入输出流上添加装饰器类来扩展其功能。
在Java SDK中,装饰器模式的完整原码如下:
// 抽象基本类
public abstract class InputStream {
public abstract int read() throws IOException;
}
// 基本类的具体实现类
public class FileInputStream extends InputStream {
// 读取文件内容
@Override
public int read() throws IOException {
// 具体的读取实现
}
}
// 抽象装饰器类
public abstract class FilterInputStream extends InputStream {
protected volatile InputStream in;
protected FilterInputStream(InputStream in) {
this.in = in;
}
}
// 装饰器类的具体实现类
public class BufferedInputStream extends FilterInputStream {
// 添加缓冲功能
public int read() throws IOException {
// 具体的读取实现,加入缓冲功能
}
}
// 客户端代码
public class Client {
public static void main(String[] args) throws IOException {
InputStream inputStream = new FileInputStream("file.txt");
InputStream bufferedInputStream = new BufferedInputStream(inputStream);
// 使用装饰器增强功能
int data = bufferedInputStream.read();
while (data != -1) {
// 处理数据
data = bufferedInputStream.read();
}
}
}
总结:
装饰器模式在Java SDK中的应用非常广泛,通过装饰器类的组合可以灵活地添加或删除功能。它遵循“开闭原则”,使得系统中的对象可以在不修改源代码的情况下进行扩展。使用装饰器模式可以实现一种动态包装机制,使得对象的增强和扩展变得非常简单和灵活。