首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

設計模式筆記:裝飾器模式 - 透明擴展對象職責

     編輯:C++ 入門

模式定義

裝飾器模式(Decorator/Wrapper):在不改變原類接口的前提下,動態地給對象添加職責。是繼承的替代方案,提供比靜態繼承更靈活的功能擴展。

角色結構

  • Component(抽象構件):定義接口規範。
  • ConcreteComponent(具體構件):被裝飾的原始對象。
  • Decorator(裝飾角色):持有 Component 引用,實現 Component 接口,委派給被裝飾對象。
  • ConcreteDecorator(具體裝飾):在委派前後添加具體行為。

代碼骨架


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();
        // 後置增強
    }
}

適用場景

  1. 需動態添加/撤銷功能。
  2. 需由基本功能排列組合產生大量變體(避免類爆炸)。
  3. 無法使用繼承(如類為 final、或繼承層次過深)。

優缺點

優點缺點
比繼承靈活,運行時決定裝飾比繼承易出錯(對象結構複雜)
避免子類爆炸,組合靈活產生大量小對象,調試困難
符合開閉原則半透明裝飾(新增公共方法)破壞透明性

簡化變體

  • 無抽象 Component:Decorator 直接繼承 ConcreteComponent。
  • 單一 ConcreteDecorator:合併 Decorator 與 ConcreteDecorator 為一類。
  • 半透明裝飾:允許新增公共方法,客戶端強轉調用(介於裝飾器與適配器之間)。

經典應用

Java IO 體系:InputStream (Component) → FileInputStream (ConcreteComponent) → FilterInputStream (Decorator) → BufferedInputStream, DataInputStream (ConcreteDecorator)。

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