[파이썬] 컴포지트 패턴과 객체 구조 표현
컴포지트 패턴은 객체 구조를 표현하기 위한 디자인 패턴으로, 복합객체와 단일객체를 동일한 방식으로 다룰 수 있게 해줍니다. 이 패턴을 사용하면 개별 객체와 그들의 조합의 차이점을 숨기고, 일관된 방식으로 처리할 수 있습니다. 이러한 패턴은 복잡한 객체 구조를 표현하고 조작하는 것을 간편하게 만들어주며, 재사용성과 유지보수성을 높일 수 있습니다.
컴포지트 패턴의 요소
컴포지트 패턴은 크게 두 가지 요소로 이루어져 있습니다:
-
Component: 복합객체와 단일객체를 동일한 인터페이스로 다루는 추상 클래스입니다. 이 클래스는 메소드를 정의하여 복합객체와 단일객체의 공통 동작을 나타냅니다.
-
Composite: 여러 개의 Component를 담을 수 있는 복합객체입니다. Composite는 Component의 서브클래스이면서, 자체적으로 또 다른 Component들을 포함할 수 있습니다.
코드 예시
다음은 Python에서 컴포지트 패턴을 구현하는 예시 코드입니다:
from abc import ABC, abstractmethod
# Component 추상 클래스
class Graphic(ABC):
@abstractmethod
def render(self):
pass
# Composite 클래스
class CompositeGraphic(Graphic):
def __init__(self):
self._graphics = []
def add(self, graphic):
self._graphics.append(graphic)
def remove(self, graphic):
self._graphics.remove(graphic)
def render(self):
for graphic in self._graphics:
graphic.render()
# Leaf 클래스
class Ellipse(Graphic):
def render(self):
print("Rendering an ellipse")
# Leaf 클래스
class Rectangle(Graphic):
def render(self):
print("Rendering a rectangle")
# Client 코드
composite = CompositeGraphic()
composite.add(Ellipse())
composite.add(Rectangle())
composite.render()
실행 결과
위의 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다:
Rendering an ellipse
Rendering a rectangle
결론
컴포지트 패턴을 사용하면 복잡한 객체 구조를 일관된 방식으로 다룰 수 있습니다. 이 패턴은 객체의 조합을 숨기고, 단일객체와 복합객체를 동일한 방식으로 다룰 수 있게 해줍니다. 이는 코드의 재사용성과 유지보수성을 높이는 데 도움을 줍니다.