裝飾器模式(Decorator/Wrapper):在不改變原類接口的前提下,動態地給對象添加職責。是繼承的替代方案,提供比靜態繼承更靈活的功能擴展。
interface Component { void operation(); }
class ConcreteComponent implements Component {
public void operation() { /* 核心邏輯 */ }
}
class Decorator implements Component {
protected Component component;
public Decorator(Component c) { this.component = c; }
public void operation() { component.operation(); } // 透明委派
}
class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component c) { super(c); }
public void operation() {
// 前置增強
super.operation();
// 後置增強
}
}
| 優點 | 缺點 |
|---|---|
| 比繼承靈活,運行時決定裝飾 | 比繼承易出錯(對象結構複雜) |
| 避免子類爆炸,組合靈活 | 產生大量小對象,調試困難 |
| 符合開閉原則 | 半透明裝飾(新增公共方法)破壞透明性 |
Java IO 體系:InputStream (Component) → FileInputStream (ConcreteComponent) → FilterInputStream (Decorator) → BufferedInputStream, DataInputStream (ConcreteDecorator)。