首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 裝飾者模式(Decorator Pattern)完整指南與實戰範例

     編輯:Java 相關知識

模式定義與核心價值

裝飾者模式屬於結構型模式,允許在不修改原類別、不使用繼承的前提下,動態為物件新增職責。它以組合取代繼承,避免「類別爆炸」,符合開放封閉原則。

角色結構

  • Component(抽象元件):定義核心介面,如 Shape。
  • ConcreteComponent(具體元件):實作核心介面,如 Circle、Rectangle。
  • Decorator(抽象裝飾者):持有 Component 引用,實作 Component 介面,轉發核心方法。
  • ConcreteDecorator(具體裝飾者):在轉發前後增加額外行為,如 RedShapeDecorator 加紅框。

完整程式碼實戰

步驟 1:定義抽象介面

public interface Shape {
    void draw();
}

步驟 2:建立具體元件

public class Rectangle implements Shape {
    @Override public void draw() { System.out.println("Shape: Rectangle"); }
}
public class Circle implements Shape {
    @Override public void draw() { System.out.println("Shape: Circle"); }
}

步驟 3:抽象裝飾基類

public abstract class ShapeDecorator implements Shape {
    protected Shape decoratedShape;
    public ShapeDecorator(Shape decoratedShape) { this.decoratedShape = decoratedShape; }
    @Override public void draw() { decoratedShape.draw(); } // 預設轉發
}

步驟 4:具體裝飾者——加紅框

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"); }
}

步驟 5:客戶端使用示範

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();
    }
}

步驟 6:執行輸出驗證

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 RedShapeDecorator(new BlueShapeDecorator(new Circle())) 疊加多種效果。
  • 函式裝飾:Java 8+ 可用 Function<T,T> 組合實現輕量裝飾,如 Stream 管線。
  • I/O 流體系:BufferedInputStream、GZIPInputStream 皆為經典裝飾者實作。

優缺點總結

優點缺點
執行期動態組合功能,避免靜態繼承爆炸產生大量細小物件,除錯較難追蹤
單一職責,每個裝飾者只關心特定邏輯過度使用導致程式碼碎片化,增加理解成本
符合開放封閉原則,新增裝飾不修改既有代碼型別檢查變複雜(instanceof 判斷特定裝飾)

總結

裝飾者模式是「付費增加功能」的經典實踐。掌握其「組合 > 繼承」的設計哲學,能讓你在需要動態擴展物件行為時,寫出優雅且可維護的代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved