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

裝飾器模式深度解析:動態擴展職責的優雅替代方案

     編輯:Java 綜合教學

模式動機

在不創建大量子類的前提下,動態地、透明地為對象添加額外職責。是繼承機制的靈活替代品。

四大角色

角色職責代碼對應
抽象組件定義核心接口,規範被裝飾對象契約Component 接口
具體組件實現核心接口,基礎功能載體ConcreteComponent 類
抽象裝飾者持有組件引用,實現組件接口,委託調用Decorator 抽象類
具體裝飾者擴展具體功能,調用 super.operation() 形成鏈ConcreteDecorator1/2 類

類結構圖

裝飾器模式類圖

Java 實現全景

1. 核心接口與基礎實現

public interface Component {
    void doSomething();
}

public class ConcreteComponent implements Component {
    @Override public void doSomething() { System.out.println("功能A"); }
}

2. 抽象裝飾者(關鍵:持有引用 + 委託)

public abstract class Decorator implements Component {
    protected Component component;
    public Decorator(Component component) { this.component = component; }
    @Override public void doSomething() { component.doSomething(); }
}

3. 具體裝飾者(疊加邏輯)

public class ConcreteDecorator1 extends Decorator {
    public ConcreteDecorator1(Component c) { super(c); }
    @Override public void doSomething() {
        super.doSomething();      // 執行被裝飾對象邏輯
        doAnotherThing();         // 新增職責
    }
    private void doAnotherThing() { System.out.println("功能B"); }
}

public class ConcreteDecorator2 extends Decorator {
    public ConcreteDecorator2(Component c) { super(c); }
    @Override public void doSomething() {
        super.doSomething();
        doAnotherThing();
    }
    private void doAnotherThing() { System.out.println("功能C"); }
}

4. 客戶端組裝(洋蔥式嵌套)

public class Test {
    public static void main(String[] args) {
        // 從內到外:Component → Decorator1 → Decorator2
        Component component = new ConcreteDecorator2(
                                new ConcreteDecorator1(
                                    new ConcreteComponent()));
        component.doSomething();
    }
}

輸出:

功能A
功能B
功能C

核心優勢與適用場景

  • 開閉原則:對擴展開放,對修改關閉。
  • 靈活組合:運行時任意排列組合功能(如 IO 流:new BufferedReader(new InputStreamReader(new FileInputStream(...))))。
  • 避免類爆炸:相比多重繼承/子類化,組合數量線性增長。

典型應用:Java IO 流體系、Servlet Filter 鏈、Spring AOP 攔截器鏈、集合包裝 Collections.synchronizedList()。

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