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

設計模式實作系列(九):Decorator 裝飾模式 - 動態為物件新增職責替代繼承

     編輯:關於C++

模式意圖

動態地給一個物件新增一些額外的職責。就增加功能來說,Decorator 模式相比生成子類更為靈活。

UML 結構圖

Decorator Pattern UML

核心解析

  • Component: 定義物件介面,可動態新增職責。
  • ConcreteComponent: 被裝飾的核心物件。
  • Decorator: 繼承 Component,持有 Component* 指標,實作 Operation() 時委派給被裝飾物件,並可在前後添加行為。
  • ConcreteDecorator: 具體裝飾類別,實作 AddedBehavior()。
  • 關鍵: 裝飾物與被裝飾物共享介面,可多層疊加(如 new DecoratorB(new DecoratorA(new Component)))。

C++ 完整實作

1. Decorator.h

#ifndef DECORATOR_H
#define DECORATOR_H

class Component {
public:
    Component() {}
    virtual ~Component() {}
    virtual void Operation() = 0;
};

class Decorator : public Component {
public:
    Decorator(Component* pComponent) : m_pComponent(pComponent) {}
    virtual ~Decorator();
protected:
    Component* m_pComponent;
};

class ConcreteComponent : public Component {
public:
    ConcreteComponent() {}
    virtual ~ConcreteComponent() {}
    virtual void Operation();
};

class ConcreteDecorator : public Decorator {
public:
    ConcreteDecorator(Component* pComponent) : Decorator(pComponent) {}
    virtual ~ConcreteDecorator() {}
    virtual void Operation();
private:
    void AddedBehavior();
};

#endif

2. Decorator.cpp

#include "Decorator.h"
#include <iostream>

Decorator::~Decorator() { delete m_pComponent; m_pComponent = nullptr; }

void ConcreteComponent::Operation() {
    std::cout << "Operation of ConcreteComponent\n";
}

void ConcreteDecorator::Operation() {
    m_pComponent->Operation(); // 委派核心行為
    AddedBehavior();           // 新增職責
}

void ConcreteDecorator::AddedBehavior() {
    std::cout << "AddedBehavior of ConcreteDecorator\n";
}

3. Main.cpp

#include "Decorator.h"
#include <cstdlib>

int main() {
    Component* pComponent = new ConcreteComponent();
    Decorator* pDecorator = new ConcreteDecorator(pComponent); // 動態裝飾
    pDecorator->Operation();
    delete pDecorator;
    return 0;
}

裝飾 vs 繼承 vs 策略

維度繼承裝飾模式策略模式
靈活性靜態、編譯期固定動態、執行期組合動態、執行期切換
疊加行為難(多重繼承複雜)易(多層包裹)單一策略(可組合策略)
介面一致性是是(透明)策略介面一致
適用場景「是一種」關係「有額外職責」關係「演算法可替換」關係

現代 C++ 與實務

  • IO 流庫(std::ostream 裝飾 std::ofstream/std::ostringstream)。
  • Java I/O、.NET Stream 皆大量使用裝飾模式。
  • C++ 可用 std::function 組合裝飾器鏈(如 HTTP 中介軟體)。

適用場景

  • GUI 視窗加滾動條/邊框/陰影。
  • 資料流壓縮/加密/緩衝層層包裹。
  • 日誌記錄、效能計時、交易邊界(AOP 切面)透明植入。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved