C++ Decorator Pattern 완벽 가이드 | 기능 동적 추가와 조합

C++ Decorator Pattern 완벽 가이드 | 기능 동적 추가와 조합

이 글의 핵심

C++ Decorator Pattern 완벽 가이드에 대한 실전 가이드입니다. 기능 동적 추가와 조합 등을 예제와 함께 상세히 설명합니다.

Decorator Pattern이란? 왜 필요한가

같은 “기능을 덧붙이기” 목적은 Python 데코레이터·JavaScript 패턴과도 맞물려 있습니다. GoF 맥락은 구조 패턴 시리즈를 참고하세요.

문제 시나리오: 기능 조합 폭발

문제: 커피에 우유, 설탕, 휘핑크림을 추가하려면, 모든 조합을 클래스로 만들어야 합니다.

// 나쁜 예: 클래스 폭발
class Coffee {};
class CoffeeWithMilk : public Coffee {};
class CoffeeWithSugar : public Coffee {};
class CoffeeWithMilkAndSugar : public Coffee {};
class CoffeeWithMilkAndSugarAndWhip : public Coffee {};
// 조합이 늘어날수록 클래스 폭발

해결: Decorator Pattern기능을 동적으로 추가합니다. Decorator가 Component를 감싸서 기능을 추가합니다.

// 좋은 예: Decorator
auto coffee = std::make_unique<SimpleCoffee>();
coffee = std::make_unique<MilkDecorator>(std::move(coffee));
coffee = std::make_unique<SugarDecorator>(std::move(coffee));
// 런타임에 기능 조합
flowchart TD
    component["Component (Coffee)"]
    simple["SimpleCoffee"]
    decorator["Decorator"]
    milk["MilkDecorator"]
    sugar["SugarDecorator"]
    
    component <|-- simple
    component <|-- decorator
    decorator <|-- milk
    decorator <|-- sugar
    decorator --> component

목차

  1. 기본 구조
  2. 스트림 데코레이터
  3. 로깅 시스템
  4. 자주 발생하는 문제와 해결법
  5. 프로덕션 패턴
  6. 완전한 예제: 텍스트 포매터

1. 기본 구조

#include <iostream>
#include <memory>
#include <string>

class Coffee {
public:
    virtual std::string getDescription() const = 0;
    virtual double cost() const = 0;
    virtual ~Coffee() = default;
};

class SimpleCoffee : public Coffee {
public:
    std::string getDescription() const override {
        return "Simple coffee";
    }
    
    double cost() const override {
        return 2.0;
    }
};

class CoffeeDecorator : public Coffee {
public:
    CoffeeDecorator(std::unique_ptr<Coffee> c)
        : coffee(std::move(c)) {}
    
protected:
    std::unique_ptr<Coffee> coffee;
};

class MilkDecorator : public CoffeeDecorator {
public:
    using CoffeeDecorator::CoffeeDecorator;
    
    std::string getDescription() const override {
        return coffee->getDescription() + " + Milk";
    }
    
    double cost() const override {
        return coffee->cost() + 0.5;
    }
};

class SugarDecorator : public CoffeeDecorator {
public:
    using CoffeeDecorator::CoffeeDecorator;
    
    std::string getDescription() const override {
        return coffee->getDescription() + " + Sugar";
    }
    
    double cost() const override {
        return coffee->cost() + 0.3;
    }
};

int main() {
    auto coffee = std::make_unique<SimpleCoffee>();
    std::cout << coffee->getDescription() << ": $" << coffee->cost() << '\n';
    
    coffee = std::make_unique<MilkDecorator>(std::move(coffee));
    std::cout << coffee->getDescription() << ": $" << coffee->cost() << '\n';
    
    coffee = std::make_unique<SugarDecorator>(std::move(coffee));
    std::cout << coffee->getDescription() << ": $" << coffee->cost() << '\n';
}

출력:

Simple coffee: $2
Simple coffee + Milk: $2.5
Simple coffee + Milk + Sugar: $2.8

2. 스트림 데코레이터

#include <iostream>
#include <memory>
#include <string>
#include <algorithm>

class DataStream {
public:
    virtual void write(const std::string& data) = 0;
    virtual std::string read() = 0;
    virtual ~DataStream() = default;
};

class FileStream : public DataStream {
public:
    void write(const std::string& data) override {
        buffer = data;
        std::cout << "[File] Written: " << data << '\n';
    }
    
    std::string read() override {
        std::cout << "[File] Reading\n";
        return buffer;
    }
    
private:
    std::string buffer;
};

class StreamDecorator : public DataStream {
public:
    StreamDecorator(std::unique_ptr<DataStream> s)
        : stream(std::move(s)) {}
    
protected:
    std::unique_ptr<DataStream> stream;
};

class EncryptionDecorator : public StreamDecorator {
public:
    using StreamDecorator::StreamDecorator;
    
    void write(const std::string& data) override {
        std::string encrypted = encrypt(data);
        std::cout << "[Encryption] Encrypting\n";
        stream->write(encrypted);
    }
    
    std::string read() override {
        std::string encrypted = stream->read();
        std::cout << "[Encryption] Decrypting\n";
        return decrypt(encrypted);
    }
    
private:
    std::string encrypt(const std::string& data) {
        std::string result = data;
        std::reverse(result.begin(), result.end());
        return result;
    }
    
    std::string decrypt(const std::string& data) {
        return encrypt(data);  // 대칭
    }
};

class CompressionDecorator : public StreamDecorator {
public:
    using StreamDecorator::StreamDecorator;
    
    void write(const std::string& data) override {
        std::string compressed = compress(data);
        std::cout << "[Compression] Compressing\n";
        stream->write(compressed);
    }
    
    std::string read() override {
        std::string compressed = stream->read();
        std::cout << "[Compression] Decompressing\n";
        return decompress(compressed);
    }
    
private:
    std::string compress(const std::string& data) {
        return "[COMPRESSED]" + data;
    }
    
    std::string decompress(const std::string& data) {
        return data.substr(12);  // "[COMPRESSED]" 제거
    }
};

int main() {
    auto stream = std::make_unique<FileStream>();
    stream = std::make_unique<EncryptionDecorator>(std::move(stream));
    stream = std::make_unique<CompressionDecorator>(std::move(stream));
    
    stream->write("Hello, World!");
    std::string data = stream->read();
    std::cout << "Result: " << data << '\n';
}

3. 로깅 시스템

#include <iostream>
#include <memory>
#include <chrono>
#include <iomanip>

class Logger {
public:
    virtual void log(const std::string& message) = 0;
    virtual ~Logger() = default;
};

class ConsoleLogger : public Logger {
public:
    void log(const std::string& message) override {
        std::cout << message << '\n';
    }
};

class LoggerDecorator : public Logger {
public:
    LoggerDecorator(std::unique_ptr<Logger> l)
        : logger(std::move(l)) {}
    
protected:
    std::unique_ptr<Logger> logger;
};

class TimestampDecorator : public LoggerDecorator {
public:
    using LoggerDecorator::LoggerDecorator;
    
    void log(const std::string& message) override {
        auto now = std::chrono::system_clock::now();
        auto time = std::chrono::system_clock::to_time_t(now);
        std::cout << "[" << std::put_time(std::localtime(&time), "%Y-%m-%d %H:%M:%S") << "] ";
        logger->log(message);
    }
};

class LevelDecorator : public LoggerDecorator {
public:
    LevelDecorator(std::unique_ptr<Logger> l, const std::string& level)
        : LoggerDecorator(std::move(l)), level_(level) {}
    
    void log(const std::string& message) override {
        logger->log("[" + level_ + "] " + message);
    }
    
private:
    std::string level_;
};

int main() {
    auto logger = std::make_unique<ConsoleLogger>();
    logger = std::make_unique<TimestampDecorator>(std::move(logger));
    logger = std::make_unique<LevelDecorator>(std::move(logger), "INFO");
    
    logger->log("Application started");
}

4. 자주 발생하는 문제와 해결법

문제 1: 타입 손실

증상: Decorator로 감싸면 원본 타입 정보 손실.

// ❌ 잘못된 사용
SimpleCoffee* simple = new SimpleCoffee();
Coffee* decorated = new MilkDecorator(simple);
// simple의 특정 메서드 호출 불가

// ✅ 해결: 필요 시 dynamic_cast
if (auto* simple = dynamic_cast<SimpleCoffee*>(decorated)) {
    simple->specificMethod();
}

문제 2: 순서 의존성

증상: Decorator 순서에 따라 결과가 다름.

// Encryption -> Compression vs Compression -> Encryption
// 결과가 다를 수 있음

5. 프로덕션 패턴

패턴 1: 빌더 스타일

class CoffeeBuilder {
    std::unique_ptr<Coffee> coffee;
public:
    CoffeeBuilder() : coffee(std::make_unique<SimpleCoffee>()) {}
    
    CoffeeBuilder& addMilk() {
        coffee = std::make_unique<MilkDecorator>(std::move(coffee));
        return *this;
    }
    
    CoffeeBuilder& addSugar() {
        coffee = std::make_unique<SugarDecorator>(std::move(coffee));
        return *this;
    }
    
    std::unique_ptr<Coffee> build() {
        return std::move(coffee);
    }
};

auto coffee = CoffeeBuilder()
    .addMilk()
    .addSugar()
    .build();

6. 완전한 예제: 텍스트 포매터

#include <iostream>
#include <memory>
#include <string>
#include <algorithm>

class TextFormatter {
public:
    virtual std::string format(const std::string& text) = 0;
    virtual ~TextFormatter() = default;
};

class PlainTextFormatter : public TextFormatter {
public:
    std::string format(const std::string& text) override {
        return text;
    }
};

class FormatterDecorator : public TextFormatter {
public:
    FormatterDecorator(std::unique_ptr<TextFormatter> f)
        : formatter(std::move(f)) {}
    
protected:
    std::unique_ptr<TextFormatter> formatter;
};

class BoldDecorator : public FormatterDecorator {
public:
    using FormatterDecorator::FormatterDecorator;
    
    std::string format(const std::string& text) override {
        return "<b>" + formatter->format(text) + "</b>";
    }
};

class ItalicDecorator : public FormatterDecorator {
public:
    using FormatterDecorator::FormatterDecorator;
    
    std::string format(const std::string& text) override {
        return "<i>" + formatter->format(text) + "</i>";
    }
};

class UpperCaseDecorator : public FormatterDecorator {
public:
    using FormatterDecorator::FormatterDecorator;
    
    std::string format(const std::string& text) override {
        std::string result = formatter->format(text);
        std::transform(result.begin(), result.end(), result.begin(), ::toupper);
        return result;
    }
};

int main() {
    auto formatter = std::make_unique<PlainTextFormatter>();
    formatter = std::make_unique<BoldDecorator>(std::move(formatter));
    formatter = std::make_unique<ItalicDecorator>(std::move(formatter));
    formatter = std::make_unique<UpperCaseDecorator>(std::move(formatter));
    
    std::cout << formatter->format("Hello, World!") << '\n';
    // <I><B>HELLO, WORLD!</B></I>
}

정리

개념설명
Decorator Pattern기능을 동적으로 추가
목적상속 없이 기능 확장
구조Component, ConcreteComponent, Decorator
장점조합 유연, OCP 준수, 런타임 추가
단점타입 손실, 순서 의존, 복잡도 증가
사용 사례스트림, 로깅, UI, 텍스트 포맷

Decorator Pattern은 기능을 동적으로 조합하는 강력한 패턴입니다.


FAQ

Q1: Decorator Pattern은 언제 쓰나요?

A: 기능을 동적으로 추가하고, 조합이 많아 상속으로 해결하기 어려울 때 사용합니다.

Q2: 상속 vs Decorator?

A: 상속은 정적, Decorator는 동적 조합이 가능합니다.

Q3: Adapter와 차이는?

A: Adapter인터페이스 변환, Decorator기능 추가에 집중합니다.

Q4: 성능 오버헤드는?

A: Decorator 체인이 길면 간접 참조가 증가합니다.

Q5: 타입 손실 문제는?

A: dynamic_cast로 원본 타입을 복원하거나, Visitor Pattern을 사용하세요.

Q6: Decorator Pattern 학습 리소스는?

A:

한 줄 요약: Decorator Pattern으로 기능을 동적으로 조합할 수 있습니다. 다음으로 Adapter Pattern을 읽어보면 좋습니다.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

  • C++ Adapter Pattern 완벽 가이드 | 인터페이스 변환과 호환성
  • C++ Proxy Pattern 완벽 가이드 | 접근 제어와 지연 로딩

관련 글

  • C++ Mixin |