徹底搞懂裝飾器模式

什麼是裝飾器模式(What)

動態的給一個對象添加一些額外的職責

爲什麼使用裝飾器模式(Why)

繼承方案會導致繼承結構複雜,不易維護等問題,因此使用組合代替繼承,給原始類添加增強功能

怎樣使用裝飾器模式(How)

裝飾器類需要和原始類繼承相同的抽象類或者實現相同的接口

下面以JDK中的IO舉例:

//抽象類輸入流
public abstract class InputStream {
    public abstract int read() throws IOException;
    public void close() throws IOException {}
}
//實現InputStream中的所有方法,讓其子類按需要覆蓋方法,並且還可以提供附加的方法或字段。
public class FilterInputStream extends InputStream {
    protected volatile InputStream in;
    protected FilterInputStream(InputStream in) {
        this.in = in;
    }
    public int read() throws IOException {
        return in.read();
    }
    public void close() throws IOException {
        in.close();
    }
}
//裝飾器類都繼承FilterInputStream,可以增強自己想要增強的功能
public class CheckedInputStream extends FilterInputStream {
    public CheckedInputStream(InputStream in, Checksum cksum) {
        super(in);
        this.cksum = cksum;
    }
    public int read() throws IOException {
        int b = in.read();
        if (b != -1) {
            cksum.update(b);
        }
        return b;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章