PHpullh
학습 라이브러리/Java/데코레이터 패턴

JAVA · 객체지향

데코레이터 패턴

기존 객체에 동적으로 기능을 추가하는 데코레이터 패턴입니다.

객체지향중급decorator데코레이터구조패턴래퍼

핵심 설명

기존 객체에 동적으로 기능을 추가하는 데코레이터 패턴입니다.

Java code

import java.util.function.Function;

public class DecoratorPattern {
    // 기본 인터페이스
    interface TextFormatter {
        String format(String text);
    }

    // 기본 구현
    static class PlainFormatter implements TextFormatter {
        public String format(String text) { return text; }
    }

    // 데코레이터 (추상)
    static abstract class FormatterDecorator implements TextFormatter {
        protected final TextFormatter wrapped;
        FormatterDecorator(TextFormatter wrapped) { this.wrapped = wrapped; }
    }

    // 구체 데코레이터들
    static class BracketDecorator extends FormatterDecorator {
        BracketDecorator(TextFormatter w) { super(w); }
        public String format(String t) { return "[" + wrapped.format(t) + "]"; }
    }

    static class UpperDecorator extends FormatterDecorator {
        UpperDecorator(TextFormatter w) { super(w); }
        public String format(String t) { return wrapped.format(t).toUpperCase(); }
    }

    // 함수형 데코레이터 (더 간결!)
    static TextFormatter decorate(TextFormatter base,
            Function<String, String>... decorators) {
        TextFormatter result = base;
        for (var d : decorators) {
            TextFormatter prev = result;
            result = text -> d.apply(prev.format(text));
        }
        return result;
    }

    public static void main(String[] args) {
        TextFormatter fmt = new BracketDecorator(
            new UpperDecorator(new PlainFormatter()));
        System.out.println(fmt.format("hello")); // [HELLO]
    }
}

학습 팁

데코레이터는 InputStream/OutputStream 계열에서 널리 사용됩니다. BufferedReader(new FileReader(f))가 대표적 예입니다.

주의할 점

데코레이터가 너무 깊게 중첩되면 디버깅이 어렵습니다. 3단계를 넘으면 파이프라인이나 빌더 패턴으로 리팩토링하세요.

자주 묻는 질문

데코레이터 패턴란 무엇인가요?

기존 객체에 동적으로 기능을 추가하는 데코레이터 패턴입니다.

데코레이터 패턴 학습 시 주의할 점은 무엇인가요?

데코레이터가 너무 깊게 중첩되면 디버깅이 어렵습니다. 3단계를 넘으면 파이프라인이나 빌더 패턴으로 리팩토링하세요.