装饰模式Decorator,也可称为包装器Wrapper。相比于用继承的方式扩展功能,装饰模式用更少的类对功能灵活组合。
(Adapter和Decorator均可称为包装器Wrapper,但Adapter是包装接口,Decorator是包装具体对象)
装饰模式包含以下四部分:
- Component 被装饰者接口
- ConcreteComponent 具体的被装饰者类
- Decorator 装饰者接口,与Component接口一致,持有Component对象的引用
- ConcreteDecorator 具体装饰者类
Java I/O类库中的filter(过滤器)类,即使用了装饰器模式。
FilterInputStream和FilterOutputStream这两个基类提供了装饰器类的接口,用于控制InputStream和OutputStream的特定输入、输出流。
Component 被装饰者接口
public abstract class InputStream implements Closeable {
public abstract int read() throws IOException;
}
ConcreteComponent 具体的被装饰者类
public class FileInputStream extends InputStream {
}
Decorator 装饰者接口
public class FilterInputStream extends InputStream {
/**
* The input stream to be filtered.
*/
protected volatile InputStream in;
public int read() throws IOException {
return in.read();
}
}
ConcreteDecorator 具体装饰者类
public class BufferedInputStream extends FilterInputStream {
}
public class DataInputStream extends FilterInputStream implements DataInput {
}
用例
public void decoratorDemo () throws FileNotFoundException {
InputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("fileName")));
}