C++ Decorator Pattern 완벽 가이드 | 기능 동적 추가와 조합
이 글의 핵심
C++ Decorator Pattern : 기능 동적 추가와 조합. 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. 기본 구조
#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:
- “Design Patterns” by Gang of Four
- “Head First Design Patterns” by Freeman & Freeman
- Refactoring Guru: Decorator Pattern 한 줄 요약: Decorator Pattern으로 기능을 동적으로 조합할 수 있습니다. 다음으로 Adapter Pattern을 읽어보면 좋습니다.
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
관련 글
심화 부록: 구현·운영 관점
이 부록은 앞선 본문에서 다룬 주제(「C++ Decorator Pattern 완벽 가이드 | 기능 동적 추가와 조합」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(I/O·네트워크·동시성) → 관측의 흐름으로 장애를 나누면 원인 추적이 빨라집니다.
내부 동작과 핵심 메커니즘
flowchart TD A[입력·요청·이벤트] --> B[파싱·검증·디코딩] B --> C[핵심 연산·상태 전이] C --> D[부작용: I/O·네트워크·동시성] D --> E[결과·관측·저장]
sequenceDiagram participant C as 클라이언트/호출자 participant B as 경계(런타임·게이트웨이·프로세스) participant D as 의존성(API·DB·큐·파일) C->>B: 요청/이벤트 B->>D: 조회·쓰기·RPC D-->>B: 지연·부분 실패·재시도 가능 B-->>C: 응답 또는 오류(코드·상관 ID)
- 불변 조건(Invariant): 버퍼 경계, 프로토콜 상태, 트랜잭션 격리, FD 상한 등 단계별로 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
- 결정성: 순수 층과 시간·네트워크·스케줄에 의존하는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
- 경계 비용: 직렬화, 인코딩, syscall 횟수, 락 경합, 할당·GC, 캐시 미스를 의심 목록에 둡니다.
- 백프레셔: 생산자가 소비자보다 빠를 때 버퍼·큐·스트림에서 속도를 줄이는 신호를 어디에 둘지 정의합니다.
프로덕션 운영 패턴
| 영역 | 운영 관점 질문 |
|---|---|
| 관측성 | 요청 단위 상관 ID, 에러율·지연 p95/p99, 의존성 타임아웃·재시도가 대시보드에 보이는가 |
| 안전성 | 입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가 |
| 신뢰성 | 재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가 |
| 성능 | 캐시·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가 |
| 배포 | 롤백 룬북, 카나리/블루그린, 마이그레이션·피처 플래그가 문서화되어 있는가 |
| 용량 | 피크 트래픽·디스크·FD·스레드 풀 상한을 주기적으로 검증하는가 |
스테이징은 데이터 양·네트워크 RTT·동시성을 프로덕션에 가깝게 맞출수록 재현율이 올라갑니다.
확장 예시: 엔드투엔드 미니 시나리오
앞선 본문 주제(「C++ Decorator Pattern 완벽 가이드 | 기능 동적 추가와 조합」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.
- 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드를 경계에 둔다.
- 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 로그·메트릭·트레이스에서 한 흐름으로 본다.
- 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
- 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지 확인한다.
- 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값을 점검한다.
handle(request):
ctx = newCorrelationId()
validated = validateSchema(request)
authorize(validated, ctx)
result = domainCore(validated)
persistOrEmit(result, idempotentKey)
recordMetrics(ctx, latency, outcome)
return result
문제 해결(Troubleshooting)
| 증상 | 가능 원인 | 조치 |
|---|---|---|
| 간헐적 실패 | 레이스, 타임아웃, 외부 의존성, DNS | 최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검 |
| 성능 저하 | N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스 | 프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거 |
| 메모리 증가 | 캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납 | 상한·TTL·힙/FD 스냅샷 비교 |
| 빌드·배포만 실패 | 환경 변수, 권한, 플랫폼 차이, lockfile | CI 로그와 로컬 diff, 런타임·이미지 버전 핀 |
| 설정 불일치 | 프로필·시크릿·기본값, 리전 | 스키마 검증된 설정 단일 소스와 배포 매트릭스 표준화 |
| 데이터 불일치 | 비멱등 재시도, 부분 쓰기, 캐시 무효화 누락 | 멱등 키·아웃박스·트랜잭션 경계 재검토 |
권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.
배포 전에는 git add → git commit → git push 후 npm run deploy 순서를 권장합니다.
이 글에서 다루는 키워드 (관련 검색어)
C++, decorator, pattern, wrapper, composition, inheritance 등으로 검색하시면 이 글이 도움이 됩니다.