首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

裝飾模式無法動態移除裝飾的本質限制與替代方案

     編輯:程式設計疑難解答

問題

裝飾模式為對象動態添加職責(穿衣服、穿鞋),但如何實現「脫鞋」(移除裝飾)?

本質限制

裝飾模式只支持疊加,不支持移除。裝飾鏈構建後為單向鏈表:

ConcreteComponent → DecoratorA → DecoratorB → DecoratorC

無法從中間移除 DecoratorB,因為 DecoratorA 持有 DecoratorB 的引用,且接口不暴露移除操作。

替代方案

  1. 重建裝飾鏈:創建新對象,僅裝飾需要的功能
    Component c = new DecoratorA(new ConcreteComponent()); // 無 DecoratorB
  2. 狀態模式:將「穿鞋/脫鞋」建模為狀態變更
    interface State { void wear(); void remove(); }
    class WithShoes implements State { ... }
    class WithoutShoes implements State { ... }
  3. 組合而非繼承:對象持有可增減的裝飾列表
    class Person {
        List decorations = new ArrayList<>();
        void add(Decorator d) { decorations.add(d); }
        void remove(Decorator d) { decorations.remove(d); }
    }

選擇建議

  • 頻繁增減裝飾 → 方案 3 (組合列表)
  • 狀態切換明確 → 方案 2 (狀態模式)
  • 靜態構建、少量變化 → 方案 1 (重建)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved