Python 디자인 패턴
Composite Pattern in Python
Treat a single item and a whole group the same way, such as a file and a folder that both report their size.
배울 내용
- Leaves and containers
- A shared interface such as size()
- Recursive totals over a tree
Sum(Number(1), Sum(Number(2), Number(3))).total()
Sum= 6Number(1)Sum= 5Number(2)Number(3)
Groups and items answer the same call
Composite는 파일과 하위 폴더가 들어 있는 폴더나 중첩된 수식처럼 트리 구조를 표현하는 디자인 패턴입니다. 핵심은 개별 요소(잎)와 요소 묶음이 같은 인터페이스를 가진다는 것입니다. 그래서 사용하는 코드는 둘을 구분할 필요가 없습니다.
핵심 포인트
- A leaf returns its own value.
- A composite asks each child and adds up the answers.
- Client code calls
total()without checking which kind it has.
언제 사용하나요?
- 검증된 구조로 반복되는 객체 설계 문제를 해결합니다.
- 책임을 분리하여 코드를 더 쉽게 확장하고 테스트할 수 있게 합니다.
- 팀에서 아키텍처를 논의할 때 공통 설계 용어를 사용합니다.
예제 코드
main.py
class Number:
# Composite: leaves and containers expose the same operation.
def __init__(self, value): self.value = value
def total(self): return self.value
class Sum:
def __init__(self, *children): self.children = children
def total(self):
# Treat leaves and nested groups uniformly.
return sum(child.total() for child in self.children)
expression = Sum(Number(1), Sum(Number(2), Number(3)))
print(expression.total())
실행 결과
6
코드 설명
Number와 Sum은 모두 total() 메서드를 가집니다. Number는 자기 값을 돌려주고, Sum은 각 자식의 total()을 호출해 결과를 더합니다. Sum 안에 또 다른 Sum이 들어갈 수 있으므로 식 Sum(Number(1), Sum(Number(2), Number(3)))은 재귀적으로 계산되어 6이 됩니다.
값을 변경하고 Python 설치 없이 CodeUtility 온라인 Python 컴파일러에서 실행하세요.
연습 문제
아래 제안을 따라 코드를 바꿔 보세요. 코드를 직접 고치고 결과를 확인하면 읽기만 할 때보다 레슨을 훨씬 잘 이해할 수 있습니다.
- 패턴 구조를 유지하면서 예제 도메인을 바꿔 보세요.
- 패턴을 더 단순한 구현과 비교하고 장단점을 설명하세요.
- 다른 구현을 추가하기 전에 각 참여 요소에 대한 테스트를 작성하세요.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
모든 챌린지