[python] 컴포지트 디자인 패턴
컴포지트 디자인 패턴은 객체들을 트리 구조로 구성하여, 개별 객체 및 객체들의 집합을 일관되게 다루기 위한 디자인 패턴입니다. 이 패턴을 사용하면 개별 객체와 그룹 객체를 동일한 방식으로 취급할 수 있어서 코드의 일관성과 재사용성을 높일 수 있습니다.
패턴 구성 요소
컴포지트 디자인 패턴은 다음과 같이 구성됩니다:
- Component: 컴포지트 패턴의 인터페이스로, 개별 객체와 그룹 객체를 동일한 방식으로 다루기 위한 메서드를 정의합니다.
- Leaf: 컴포지트 패턴의 단일 객체를 나타냅니다. Leaf는 다른 객체를 포함하지 않고, 컴포지트 패턴의 메서드를 구현합니다.
- Composite: 컴포지트 패턴의 그룹 객체를 나타냅니다. Composite는 다른 객체를 포함하고, 그룹 객체에 대한 작업을 수행하기 위해 컴포지트 패턴의 메서드를 구현합니다.
예제
class Component:
def operation(self):
raise NotImplementedError()
class Leaf(Component):
def operation(self):
print("Leaf operation")
class Composite(Component):
def __init__(self):
self.children = []
def add(self, component):
self.children.append(component)
def remove(self, component):
self.children.remove(component)
def operation(self):
for child in self.children:
child.operation()
위의 예제에서 Component
는 인터페이스를 정의하며, Leaf
와 Composite
는 Component
클래스를 구현합니다. Leaf
는 단일 객체를 나타내고, Composite
는 그룹 객체를 나타냅니다.
사용 예시
root = Composite()
child1 = Leaf()
child2 = Composite()
child3 = Leaf()
root.add(child1)
root.add(child2)
child2.add(child3)
root.operation()
위의 예시에서 root
는 Composite
객체이며, child1
과 child2
를 포함합니다. child2
는 또 다른 Composite
객체이며, child3
를 포함합니다. root.operation()
을 호출하면 root
의 자식 객체인 child1
, child2
, child3
의 operation()
메서드가 순서대로 호출됩니다.
결론
컴포지트 디자인 패턴은 개별 객체와 그룹 객체를 동일한 방식으로 다룰 수 있도록 해줍니다. 이를 통해 코드의 일관성과 재사용성을 높일 수 있습니다. 컴포지트 디자인 패턴은 트리 구조를 다루는 알고리즘 및 자료구조에서 유용하게 활용될 수 있습니다.