裝飾器模式 允許在不改變現有對象結構的情況下,動態地給對象添加新功能。屬於結構型模式,通過「包裝」實現功能疊加,是繼承的有力替代方案——組合優於繼承。
核心角色:
Shape。Circle、Rectangle。RedShapeDecorator 添加紅色邊框。public interface Shape {
void draw();
}
public class Circle implements Shape {
@Override public void draw() { System.out.println("Shape: Circle"); }
}
public class Rectangle implements Shape {
@Override public void draw() { System.out.println("Shape: Rectangle"); }
}
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape) { this.decoratedShape = decoratedShape; }
@Override public void draw() { decoratedShape.draw(); } // 默認委託
}
public class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) { super(decoratedShape); }
@Override public void draw() {
decoratedShape.draw(); // 1. 原有繪製
setRedBorder(decoratedShape); // 2. 新增功能
}
private void setRedBorder(Shape s) { System.out.println("Border Color: Red"); }
}
public class DecoratorPatternDemo {
public static void main(String[] args) {
Shape circle = new Circle();
Shape redCircle = new RedShapeDecorator(new Circle());
Shape redRectangle = new RedShapeDecorator(new Rectangle());
System.out.println("Circle with normal border"); circle.draw();
System.out.println("\nCircle of red border"); redCircle.draw();
System.out.println("\nRectangle of red border"); redRectangle.draw();
}
}
/* 輸出:
Circle with normal border
Shape: Circle
Circle of red border
Shape: Circle
Border Color: Red
Rectangle of red border
Shape: Rectangle
Border Color: Red
*/
| 優勢 | 說明 |
|---|---|
| 動態擴展 | 運行時決定添加哪些功能,無需創建爆炸式子類 |
| 單一職責 | 每個裝飾器只關注一項具體功能(如加邊框、加滾動條、加壓縮) |
| 開閉原則 | 新增裝飾器不修改原有代碼 |
| 靈活組合 | 可任意嵌套:new RedBorder(new Scrollable(new Compressed(new FileSource()))) |
典型應用:
BufferedInputStream、GZIPInputStream、DataInputStream 層層包裝 InputStream。TransactionProxyFactoryBean、AOP 代理鏈。| 維度 | 繼承 | 裝飾器 | 靜態代理 |
|---|---|---|---|
| 關係 | is-a | has-a (包裝) | has-a (代理) |
| 擴展時機 | 編譯期 | 運行期 | 編譯期/運行期 |
| 功能疊加 | 困難(類爆炸) | 極易(嵌套) | 需手動組合 |
| 透明性 | 完全透明 | 對客戶端透明 | 對客戶端透明 |
裝飾器模式以「包裝+委託」實現職責的動態疊加,完美詮釋了「組合優於繼承」。從 Java I/O 到 Spring AOP,它是框架設計中實現橫切關注點、保持核心邏輯純淨的基石。掌握其精髓:**接口統一、持有引用、委託調用、前後增強**,即可靈活應對各種功能擴展場景。