Python 디자인 패턴
Decorator Pattern in Python
Wrap an object to add behavior, such as logging or uppercasing, without editing its class. Stack as many wrappers as you need.
배울 내용
- Wrapping an object with the same interface
- Stacking several decorators
- How this relates to Python's @decorator syntax
Logger(Uppercase(Message("hello")))
Loggeradds "LOG: "LOG: HELLOUppercaseuppercasesHELLOMessagethe originalhello
Wrappers around the same interface
Decorator는 객체를 같은 인터페이스를 가진 다른 객체로 감싼 다음, 결과에 동작을 덧붙이는 디자인 패턴입니다. 감싸는 객체는 여러 방식으로 겹쳐 쌓을 수 있어서, 하위 클래스를 만들지 않고도 기능을 유연하게 조합할 수 있습니다. 생각은 비슷하지만 이 패턴은 Python의 @decorator 문법과는 다르다는 점에 주의하세요.
핵심 포인트
- A decorator holds the wrapped object and offers the same method.
- It calls the inner object, then changes or extends the result.
- Decorators can be stacked in any order.
언제 사용하나요?
- 검증된 구조로 반복되는 객체 설계 문제를 해결합니다.
- 책임을 분리하여 코드를 더 쉽게 확장하고 테스트할 수 있게 합니다.
- 팀에서 아키텍처를 논의할 때 공통 설계 용어를 사용합니다.
예제 코드
main.py
class Message:
# Decorator: wrap an object to add behavior dynamically.
def render(self): return "hello"
class Uppercase:
def __init__(self, wrapped): self.wrapped = wrapped
def render(self): return self.wrapped.render().upper()
class Logger:
def __init__(self, wrapped): self.wrapped = wrapped
def render(self):
# Add behavior while preserving the render interface.
return "LOG: " + self.wrapped.render()
print(Logger(Uppercase(Message())).render())
실행 결과
LOG: HELLO
코드 설명
Uppercase는 Message 객체를 감싸 결과를 대문자로 바꾸고, Logger는 Uppercase를 감싸 LOG: 접두사를 붙입니다. 세 클래스 모두 render() 메서드를 가지므로 어떤 순서로든 서로를 감쌀 수 있습니다. 최종 결과는 LOG: HELLO입니다.
값을 변경하고 Python 설치 없이 CodeUtility 온라인 Python 컴파일러에서 실행하세요.
연습 문제
아래 제안을 따라 코드를 바꿔 보세요. 코드를 직접 고치고 결과를 확인하면 읽기만 할 때보다 레슨을 훨씬 잘 이해할 수 있습니다.
- 패턴 구조를 유지하면서 예제 도메인을 바꿔 보세요.
- 패턴을 더 단순한 구현과 비교하고 장단점을 설명하세요.
- 다른 구현을 추가하기 전에 각 참여 요소에 대한 테스트를 작성하세요.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
모든 챌린지