天天看點

結構型模式之裝飾模式

裝飾模式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")));
}           

繼續閱讀