[Python] Composite Design Pattern

미남잉·4일 전
0

Advanced Python

목록 보기
10/10
post-thumbnail

Composite Design Pattern은 객체들을 트리 구조로 구성하여 부분-전체 관계를 표현하는 구조적 디자인 패턴이다. 이 패턴은 개별 객체와 객체 그룹을 동일한 방식으로 다룰 수 있게 해준다.

주요 특징

  • 부분(개별 객체)과 전체(복합 객체)를 동일한 인터페이스로 처리할 수 있게 함
  • 객체들을 변경 가능한 트리 구조로 구성할 수 있음
  • 계층적 관계를 쉽게 관리하고 재구성할 수 있음
  • 객체 계층 구조에 대해 재귀적으로 메서드를 실행하고 결과를 합산할 수 있음

구성 요소

Composite패턴은 주로 다음 세 가지 요소로 구성됨:
1. Component(구성요소): 모든 객체에 대한 공통 인터페이스를 정의
2. Leaf(잎): 복합체의 기본 객체로, 자식이 없는 개별 객체
3. Composite(복합체): 자식 구성요소를 포함하는 복합 객체

코드 설명

(1) 추상 클래스 (인터페이스 역할)

from abc import ABCMeta, abstractmethod, abstractstaticmethod

class IDepartment(metaclass=ABCMeta):
    @abstractmethod
    def __init__(self, employees):
        """ Implement in child class """

    @abstractstaticmethod
    def print_department():
        """ Implement in child class """
  • IDepartment 클래스는 추상 클래스(인터페이스 역할) 로, 모든 부서 클래스가 따라야 할 공통적인 구조를 정의함
  • @abstractmethod@abstractstaticmethod 를 사용하여 자식 클래스에서 반드시 구현해야 하는 메서드를 강제함

(2) Leaf 클래스 (Accounting, Development)

class Accounting(IDepartment):
    def __init__(self, employees):
        self.employees = employees

    def print_department(self):
        print(f"Accounting Department: {self.employees}")
class Development(IDepartment):
    def __init__(self, employees):
        self.employees = employees

    def print_department(self):
        print(f"Development Department: {self.employees}")
  • AccountingDevelopment 클래스는 개별 부서를 나타내는 Leaf(잎) 객체
  • print_department() 메서드를 통해 각 부서의 직원 수를 출력

(3) Composite 클래스 (ParentDepartment)

class ParentDepartment(IDepartment):
    def __init__(self, employees):
        self.employees = employees
        self.base_employees = employees
        self.sub_depts = []

    def add(self, dept):
        self.sub_depts.append(dept)
        self.employees += dept.employees

    def print_department(self):
        print("Parent Department")
        print(f"Parent Department Base Employees: {self.base_employees}")
        for dept in self.sub_depts:
            dept.print_department()
        print(f"Total number of employees: {self.employees}")
  • ParentDepartment 클래스는 Composite(합성) 객체로, 여러 개의 부서를 포함할 수 있음
  • add(self, dept) 메서드를 통해 하위 부서(Accounting, Development)를 추가할 수 있음
  • print_department() 메서드를 실행하면, 자신의 직원 수 + 하위 부서 직원 수를 출력

핵심 개념

위 코드는 Composite Design Pattern을 활용하여 트리 구조를 만들고 있다.

1) Component (구성 요소)

  • IDepartment 가 공통 인터페이스 역할
  • print_department() 같은 메서드를 강제하여 일관된 동작을 보장

2) Leaf (잎 노드)

  • Accounting, Development 클래스가 여기에 해당
  • 더 이상 하위 부서를 가지지 않고, 독립적으로 동작하는 부서

3) Composite (합성 노드)

  • ParentDepartment 가 합성 객체로서 역할
  • 여러 부서를 포함하고, 하위 부서의 직원 수를 합산하여 관리

실행 예시

(1) 객체 생성 및 추가

if __name__ == "__main__":
    accounting = Accounting(200)
    development = Development(300)

    parent_dept = ParentDepartment(100)
    parent_dept.add(accounting)
    parent_dept.add(development)

    parent_dept.print_department()

(2) 실행 결과

Parent Department
Parent Department Base Employees: 100
Accounting Department: 200
Development Department: 300
Total number of employees: 600
ParentDepartment 에는 기본적으로 100명의 직원이 있습니다.
  • Accounting(200명)과 Development(300명)을 추가하면, 총 직원 수가 600명으로 출력

Composite Pattern 의 장점

  • 트리 구조 표현이 용이
  • 개별 객체(Leaf)와 그룹(Composite)을 동일하게 다룰 수 있음
  • 유연한 객체 추가/삭제 가능 (객체 관리가 편리함)
  • OCP(개방-폐쇄 원칙) 준수 → 새로운 부서를 추가해도 기존 코드 수정 최소화

이 코드에서 새로운 부서를 추가하려면, class HR(IDepartment): 처럼 새로운 클래스를 만들고 ParentDepartment 에 추가하면 됨

결론

  • Composite 패턴은 트리 구조로 구성된 객체들을 동일한 방식으로 다룰 수 있도록 하는 패턴임
  • 위 코드는 조직 내 부서 관리 시스템을 예제로 Composite 패턴을 활용한 구현
  • Leaf (개별 부서)Composite (부서 그룹)를 동일한 인터페이스로 처리할 수 있도록 설계되어 있음
profile
Computer Vision Engineer

0개의 댓글

관련 채용 정보