데코레이터 패턴
같은 호출 약속을 유지하는 객체를 감싸 부가 기능을 조합하고, 감싸는 순서가 결과를 바꾸는 이유.
· 마지막 업데이트: 2026-11-05 · 15 min read
개요
본문만 찍어내던 보고서에 화면마다 다른 장식을 붙여야 할 때가 있다. 어떤 화면은 머리말 제목을 원하고, 어떤 화면은 줄 번호를 원하며, 또 어떤 화면은 둘 다 원하는데, 이 조합마다 하위 클래스를 따로 파기 시작하면 옵션 하나가 추가될 때마다 클래스 개수가 곱절로 불어나니 각 기능을 독립된 포장 객체로 쪼개어 필요한 순서대로 겹겹이 감싸는 편이 훨씬 낫다.
알맹이 본문은 맨 안쪽 객체가 만들고, 바깥을 감싸는 포장 객체들은 각자 자기 몫의 가공만 덧붙인다. 이처럼 원래 객체와 똑같은 인터페이스(IReport)를 유지한 채 객체를 감싸서 책임을 더하는 구조가 데코레이터(Decorator) 패턴이며, 호출부 입장에서는 한 겹을 감쌌든 세 겹을 감쌌든 똑같이 Render()만 부르면 된다.
UML
UML을 보면 역할 분담이 한눈에 들어온다. 알맹이인 TextReport가 기본 본문을 내놓고, 포장지인 TitleReport와 NumberedReport는 자기도 IReport를 구현하면서 동시에 내부 필드로 또 다른 IReport(inner)를 품고 있다가 inner.Render()가 돌려준 문자열 앞뒤에 제목이나 줄 번호를 덧대어 반환하는데, 굳이 추상 데코레이터 부모 클래스를 따로 두지 않고 각 포장 클래스가 인터페이스를 직접 구현해도 패턴은 똑같이 성립한다.
아래 객체 다이어그램은 TitleReport(NumberedReport(TextReport))로 포갠 한 가지 조합을 따라간다. 호출은 바깥(TitleReport)에서 안쪽(TextReport)으로 파고들고, 만들어진 본문이 밖으로 빠져나오면서 줄 번호가 먼저 붙고 맨 마지막에 제목이 얹힌다.
역사
1994년 GoF(Gamma, Helm, Johnson, Vlissides)는 Design Patterns에서 Decorator를 구조 패턴으로 정리했다.1
표준 라이브러리에서도 이 구조는 일찍부터 쓰였다. Java 1.0 I/O 라이브러리의 FilterInputStream은 InputStream을 상속하는 동시에 내부에 또 다른 InputStream을 품고 기본 읽기 호출을 그 안쪽 객체로 위임하는데, 하위 클래스가 그 앞뒤에 데이터 변환이나 버퍼링 같은 부가 기능을 덧입힐 수 있게 한 전형적인 객체 조합 패턴이다(특정 언어의 @decorator 문법을 가리키는 이름이 아니다).2
왜 사용하는가?
제목·줄 번호·로깅을 상속으로만 풀려 들면 TitledReport, NumberedReport, TitledNumberedReport처럼 조합 경우의 수를 일일이 클래스 이름으로 찍어내야 한다. 반면 데코레이터는 기능 조각을 별도 객체로 만들어 둔 뒤 생성 시점에 레고 블록처럼 끼워 맞추므로, 똑같은 TextReport 알맹이 하나를 여러 조합에 그대로 재사용할 수 있다.
다만 같은 인터페이스를 구현한다는 약속은 단순히 반환 타입만 맞춘다는 뜻이 아니다! 문자열만 조합해 돌려줄 줄 알았던 Render()가 뒤에서 몰래 네트워크로 보고서를 전송하거나 호출부가 예상치 못한 예외를 던지면 감싼 의미가 무너지므로, 로깅이나 캐싱처럼 부수 효과와 실행 조건이 있는 포장지라면 조립 코드와 정책에서 그 사실이 명확히 드러나야 한다.
알고리즘 알맹이를 통째로 갈아끼우는 전략(Strategy) 패턴과 달리, 데코레이터는 안쪽 객체가 한 일을 그대로 받아 그 둘레에 책임을 덧입힌다. 고정된 변환 한 번뿐이라면 함수 하나로 끝내면 그만이다.
예제
using System;
using System.Linq;
IReport plain = new TextReport("Revenue: 100\nCost: 40");
IReport first = new TitleReport(new NumberedReport(plain), "October");
IReport second = new NumberedReport(new TitleReport(plain, "October"));
Console.WriteLine(first.Render());
Console.WriteLine("---");
Console.WriteLine(second.Render());
// 본문과 포장 객체가 같은 호출 약속을 제공해야 연속해서 감쌀 수 있다.
public interface IReport
{
string Render();
}
public sealed class TextReport : IReport
{
private readonly string text;
public TextReport(string text) => this.text = text;
public string Render() => text;
}
// 원래 결과를 다시 구현하지 않고 안쪽 객체의 결과에 자기 기능만 더한다.
public sealed class TitleReport : IReport
{
private readonly IReport inner;
private readonly string title;
public TitleReport(IReport inner, string title)
{
this.inner = inner;
this.title = title;
}
public string Render() => title + "\n" + inner.Render();
}
public sealed class NumberedReport : IReport
{
private readonly IReport inner;
public NumberedReport(IReport inner) => this.inner = inner;
public string Render() => string.Join("\n", inner.Render().Split('\n')
.Select((line, index) => $"{index + 1}. {line}"));
}October
1. Revenue: 100
2. Cost: 40
---
1. October
2. Revenue: 100
3. Cost: 40순서가 곧 결과다. 첫 번째 조합은 본문에 줄 번호부터 매긴 뒤 바깥에서 October 제목을 얹었으니 제목에는 번호가 안 붙지만, 두 번째 조합은 제목을 먼저 붙인 결과 전체를 줄 번호 데코레이터로 감쌌기 때문에 제목인 October가 1번 줄이 되며, 이처럼 호출부가 부르는 메서드는 똑같은 Render()여도 누가 가장 바깥에 서느냐가 누가 마지막에 손을 대느냐를 결정한다.
두 조합은 같은 plain 객체를 참조한다. 예제의 포장 객체들은 문자열을 새로 만들 뿐이고, TextReport가 가진 본문 자체는 건드리지 않는다. 포장을 여러 겹 쌓아도 원본은 하나라는 뜻이다.
확장 예제
로그와 캐시의 순서
이번에는 문자열 꾸미기가 아니라 실행 흐름을 바꾸는 캐시(Cache)와 로깅(Logging) 데코레이터를 포개 보자. 캐시는 한 번 성공한 결과를 기억해 두었다가 다음 호출 때 안쪽 객체를 부르지 않고 곧장 돌려주며, 로깅은 호출이 지나갔다는 발자국을 남기는데, 둘 다 똑같은 인터페이스를 쓰더라도 누구를 바깥에 세우느냐에 따라 로그에 찍히는 숫자가 완전히 달라진다.
캐시에 남는 것은 성공한 보고서뿐이고, 실패는 그대로 반환된다. 결과는 ReportResult.Success와 ReportResult.Failure로 갈라지고, 로그에는 본문이 아니라 고정된 호출 표시만 남는다. SampleReport는 호출 횟수와 첫 실패를 드러내기 위한 대역이다. 대역이 실패를 한 번 흉내 내 주니, 캐시가 실패를 어떻게 다루는지가 한눈에 보인다.
using System;
using System.Collections.Generic;
var firstSource = new SampleReport();
var firstLog = new List<string>();
IReport cacheOutside = new CachedReport(new LoggedReport(firstSource, firstLog));
_ = cacheOutside.Render();
_ = cacheOutside.Render();
Console.WriteLine($"Cache outside: source={firstSource.Calls}, logs={firstLog.Count}");
var secondSource = new SampleReport();
var secondLog = new List<string>();
IReport logOutside = new LoggedReport(new CachedReport(secondSource), secondLog);
_ = logOutside.Render();
_ = logOutside.Render();
Console.WriteLine($"Log outside: source={secondSource.Calls}, logs={secondLog.Count}");
var failingSource = new SampleReport(failFirst: true);
IReport recoverable = new CachedReport(failingSource);
Console.WriteLine($"First failed: {recoverable.Render() is ReportResult.Failure}");
Console.WriteLine($"Second succeeded: {recoverable.Render() is ReportResult.Success}");
_ = recoverable.Render();
Console.WriteLine($"Source calls after three requests: {failingSource.Calls}");
public enum ReportError { Unavailable }
public abstract record ReportResult
{
private ReportResult() { }
public sealed record Success(string Text) : ReportResult;
public sealed record Failure(ReportError Code) : ReportResult;
}
// 본문과 포장 객체가 같은 호출 약속을 제공해야 연속해서 감쌀 수 있다.
public interface IReport
{
ReportResult Render();
}
public sealed class SampleReport : IReport
{
private readonly bool failFirst;
public int Calls { get; private set; }
public SampleReport(bool failFirst = false) => this.failFirst = failFirst;
public ReportResult Render()
{
Calls++;
if (failFirst && Calls == 1)
return new ReportResult.Failure(ReportError.Unavailable);
return new ReportResult.Success("Revenue: 100");
}
}
public sealed class LoggedReport : IReport
{
private readonly IReport inner;
private readonly List<string> log;
public LoggedReport(IReport inner, List<string> log)
{
this.inner = inner;
this.log = log;
}
public ReportResult Render()
{
log.Add("render requested");
return inner.Render();
}
}
public sealed class CachedReport : IReport
{
private readonly IReport inner;
private ReportResult.Success? cached;
public CachedReport(IReport inner) => this.inner = inner;
public ReportResult Render()
{
if (cached is not null)
return cached;
ReportResult result = inner.Render();
if (result is ReportResult.Success success)
cached = success;
return result;
}
}Cache outside: source=1, logs=1
Log outside: source=1, logs=2
First failed: True
Second succeeded: True
Source calls after three requests: 2캐시를 맨 바깥에 세우면 두 번째 요청은 캐시 선에서 바로 돌아가 버리므로 안쪽에 있는 로깅 데코레이터까지 내려가지조차 않아 로그가 딱 한 번만 찍힌다. 거꾸로 로깅을 바깥에 세우면 들어오는 모든 요청마다 로그가 꼬박꼬박 쌓이면서도 무거운 본문 생성은 안쪽 캐시 덕분에 여전히 한 번만 실행되니, 결국 ‘무엇을 세고 싶은가(전체 유입 요청 수인가, 캐시 미스 후 실제 생성 횟수인가)’가 감싸는 순서를 결정한다.
첫 결과가 실패였다면 아무것도 저장되지 않는다. 두 번째 요청에서 원본을 다시 호출해 성공한 값이 잡히고, 세 번째 요청은 그 값을 쓴다. 첫 요청 안에서 자동으로 재시도한 것이 아니라, 호출부가 세 번 따로 요청한 결과다. 실패를 남기지 않는다는 규칙 하나가 이 세 번의 흐름을 만든다.
순서를 검토할 때
만약 모든 접근을 빠짐없이 기록해야 하는 보안 감사 로그나 요청마다 호출자 자격을 따져야 하는 권한 검사를 캐시 안쪽에 넣어 버리면 어떻게 될까? 첫 호출이 캐시를 통과한 뒤부터는 캐시가 보관된 결과를 바로 내주느라 안쪽의 감사 로그와 권한 검사를 통째로 건너뛰어 버리므로, 첫 사용자가 열람한 보고서가 권한 없는 다른 사용자에게 그대로 노출되는 대형 사고로 이어진다.
또한 예제의 단순 캐시는 단일 스레드에서 변하지 않는 보고서를 가정했을 뿐이다. 실무에서 원본 데이터가 바뀌거나 시각·사용자 권한별로 결과가 달라진다면 캐시 키 설계와 무효화 정책이 함께 들어가야 하고, 입출력 스트림을 감싸는 데코레이터라면 바깥 스트림을 닫을 때 안쪽 스트림까지 누가 책임지고 닫을지도 조립 시점에 분명히 정해야 한다.
TypeScript 예제
본문, 제목, 줄 번호를 각각 객체로 두면 필요한 조합만 골라 감싸면 된다. 포장 객체가 모두 같은 IReport 약속을 지키므로, 호출부는 조합별 클래스 이름을 알 필요가 없다. 조합이 몇 겹이든 호출부 코드는 그대로다.
// 본문과 포장 객체가 같은 호출 약속을 제공해야 연속해서 감쌀 수 있다.
interface IReport { render(): string; }
class TextReport implements IReport {
constructor(private readonly text: string) {}
render(): string { return this.text; }
}
// 원래 결과를 다시 구현하지 않고 안쪽 객체의 결과에 자기 기능만 더한다.
class TitleReport implements IReport {
constructor(private readonly inner: IReport, private readonly title: string) {}
render(): string { return this.title + "\n" + this.inner.render(); }
}
class NumberedReport implements IReport {
constructor(private readonly inner: IReport) {}
render(): string {
return this.inner.render().split("\n").map((line, index) => (index + 1) + ". " + line).join("\n");
}
}
const plain = new TextReport("Revenue: 100\nCost: 40");
console.log(new TitleReport(new NumberedReport(plain), "October").render());
console.log("---");
console.log(new NumberedReport(new TitleReport(plain, "October")).render());October
1. Revenue: 100
2. Cost: 40
---
1. October
2. Revenue: 100
3. Cost: 40이 코드가 쓰는 것은 TypeScript의 @데코레이터 문법이 아니라 객체를 감싸는 GoF 패턴이다. 줄 번호를 먼저 붙이느냐 제목을 먼저 붙이느냐에 따라 출력이 달라진다.
같은 타입의 계약을 감싸는 Decorator<T>
Component<T>와 Decorator<T>는 모두 Operation()으로 T를 돌려준다. 데코레이터는 안쪽 객체를 호출한 뒤 결과에 부가 처리를 적용하므로, 호출부가 받는 타입은 유지하면서 여러 겹으로 감쌀 수 있다.
아래에서는 3을 주는 컴포넌트에 더하기 1과 곱하기 2를 감싼다. 같은 Decorator<int>끼리도 순서에 따라 8과 7이 나오며, 이 차이는 타입이 아니라 실제 호출 순서에서 생긴다. 제네릭으로 바꿔도 데코레이터의 핵심인 같은 계약과 감싸는 순서는 남는다.
C#
using System;
IComponent<int> component = new Component<int>(() => 3);
var multiplyAfterAdd = new Decorator<int>(new Decorator<int>(component, x => x + 1), x => x * 2);
var addAfterMultiply = new Decorator<int>(new Decorator<int>(component, x => x * 2), x => x + 1);
Console.WriteLine(multiplyAfterAdd.Operation());
Console.WriteLine(addAfterMultiply.Operation());
// TYPES
interface IComponent<T> { T Operation(); }
sealed class Component<T> : IComponent<T>
{
private readonly Func<T> operation;
public Component(Func<T> operation) { this.operation = operation; }
public T Operation() => operation();
}
sealed class Decorator<T> : IComponent<T>
{
private readonly IComponent<T> inner;
private readonly Func<T, T> decorate;
public Decorator(IComponent<T> inner, Func<T, T> decorate)
{ this.inner = inner; this.decorate = decorate; }
// 안쪽 호출 결과에만 부가 처리를 적용하며 같은 T 계약을 유지한다.
public T Operation() => decorate(inner.Operation());
}8
7TypeScript
interface Component<T> { operation(): T; }
class ValueComponent<T> implements Component<T> {
constructor(private readonly produce: () => T) {}
operation(): T { return this.produce(); }
}
class Decorator<T> implements Component<T> {
constructor(private readonly inner: Component<T>, private readonly decorate: (value: T) => T) {}
// 안쪽 객체와 바깥 객체가 같은 호출 약속을 지킨다.
operation(): T { return this.decorate(this.inner.operation()); }
}
const component: Component<number> = new ValueComponent(() => 3);
const multiplyAfterAdd = new Decorator(new Decorator(component, x => x + 1), x => x * 2);
const addAfterMultiply = new Decorator(new Decorator(component, x => x * 2), x => x + 1);
console.log(multiplyAfterAdd.operation());
console.log(addAfterMultiply.operation());8
7이 단순형은 같은 T를 받아 같은 T를 돌려주는 부가 처리에 맞춘 것이다. int 결과를 문자열로 바꾸고 싶다면 호출 계약도 달라지므로, 같은 계약을 유지하는 이 데코레이터와 구별해서 설계한다. 이 구조가 감싸는 대상은 결과 타입이 그대로인 처리다.
타입 매개변수와 라이브러리 계약의 문법은 공식 문서에서 확인할 수 있다.3
같이 보기
각주
- Gamma, Helm, Johnson, Vlissides. Design Patterns (1994), Decorator. 출판사 서지. ↩
- Oracle. FilterInputStream, Since 1.0. 기존 입력 스트림을 감싸 호출을 위임하는 API. ↩
- C# generics; TypeScript generics ↩