Decorator Patterns InputStream and OutputStream in the Java SDK
Decorator pattern is a structural design pattern that dynamically adds functionality without changing existing objects. The InputStream and OutputStream in the Java SDK use the decorator pattern.
InputStream and OutputStream are abstract classes that provide basic support for I/O operations. The decorator pattern extends its functionality by adding decorator classes to the basic input and output streams.
In the Java SDK, the complete source code for the decorator mode is as follows:
//Abstract Basic Class
public abstract class InputStream {
public abstract int read() throws IOException;
}
//Specific implementation classes of basic classes
public class FileInputStream extends InputStream {
//Read File Content
@Override
public int read() throws IOException {
//Specific reading implementation
}
}
//Abstract Decorator Class
public abstract class FilterInputStream extends InputStream {
protected volatile InputStream in;
protected FilterInputStream(InputStream in) {
this.in = in;
}
}
//The specific implementation class of the decorator class
public class BufferedInputStream extends FilterInputStream {
//Add buffering function
public int read() throws IOException {
//Specific reading implementation, including buffering function
}
}
//Client code
public class Client {
public static void main(String[] args) throws IOException {
InputStream inputStream = new FileInputStream("file.txt");
InputStream bufferedInputStream = new BufferedInputStream(inputStream);
//Using decorators to enhance functionality
int data = bufferedInputStream.read();
while (data != -1) {
//Processing data
data = bufferedInputStream.read();
}
}
}
Summary:
The decorator pattern is widely used in Java SDK, and through the combination of decorator classes, functions can be flexibly added or removed. It follows the "Open–closed principle", so that objects in the system can be extended without modifying the source code. Using the decorator pattern can achieve a dynamic wrapping mechanism that makes object enhancement and extension very simple and flexible.