Computer Science/Design Pattern

[Design Pattern] 컴포지트 패턴 (Composite Pattern)

dbssk 2023. 10. 8. 07:28

컴포지트 패턴(Composite Pattern)

  • 객체들을 트리 구조로 구성하여 전체-부분 계층 구조를 나타내는 데 사용되는 패턴
  • 즉, 객체들을 트리 구조로 구성한 다음 이것을 개별 객체인 것처럼 사용할 수 있다.
  • 구성 요소
    • Component : 구성에 포함된 객체들의 인터페이스를 선언하고 이러한 자식 구성 요소에 대한 액세스 및 관리를 위한 메서드를 구현한다. 즉, 모든 클래스에 해당하는 공통의 행동을 구현한다.
    • Leaf : 자식이 없는 가장 끝 객체로 실제 작업을 수행한다.
    • Composite(Container) : 자식 구성 요소를 저장하고 구성 요소 인터페이스에서 자식 관련 작업을 구현한다. 즉, 복합체는 자식 구성 요소를 포함하는 컨테이너 역할을 한다.
    • Client : 구성 수조의 객체들과 상호 작용하기 위해 구성 요소 클래스 인터페이스를 사용한다. 요청이 leaf인 경우에는 바로 처리되고, composite인 경우에는 일반적으로 요청을 자식 구성 요소로 전달하며 전달하기 전/후에 추가 작업을 수행할 수 있다.

  • 장점
    • 개별 객체와 복합 객체를 동일한 방식으로 다룰 수 있으므로, 클라이언트 코드는 객체의 구조를 신경 쓰지 않고 작성할 수 있다. 즉, 새로운 개별 객체나 복합 객체를 추가하거나 수정할 때 유용하다.
    • 객체들을 공통 인터페이스를 통해 처리할 수 있기 때문에 코드 재사용에 용이하다.

  • 단점
    • 객체의 클래스 계층 구조가 복잡해 질 수 있다.
    • 복합 객체의 구조가 변하거나, 개별 객체와 복합 객체의 인터페이스가 다른 경우에는 사용하기 힘들다.

 

컴포지트 패턴 구현

import java.util.ArrayList;
import java.util.List;

// Component 인터페이스
interface Employee {
    String getName();
    double getSalary();
}

// Leaf 클래스: 개별 직원
class IndividualEmployee implements Employee {
    private String name;
    private double salary;

    public IndividualEmployee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public double getSalary() {
        return salary;
    }
}

// Composite 클래스: 부서
class Department implements Employee {
    private String name;
    private List<Employee> employees = new ArrayList<>();

    public Department(String name) {
        this.name = name;
    }

    public void addEmployee(Employee employee) {
        employees.add(employee);
    }

    public void removeEmployee(Employee employee) {
        employees.remove(employee);
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public double getSalary() {
        double totalSalary = 0;
        for (Employee employee : employees) {
            totalSalary += employee.getSalary();
        }
        return totalSalary;
    }
}

public class CompositePatternExample {
    public static void main(String[] args) {
        // 개별 직원 생성
        Employee emp1 = new IndividualEmployee("John", 50000);
        Employee emp2 = new IndividualEmployee("Alice", 60000);

        // 부서 생성
        Department engineering = new Department("Engineering");
        Department marketing = new Department("Marketing");

        // 부서에 직원 추가
        engineering.addEmployee(emp1);
        marketing.addEmployee(emp2);

        // 전체 조직 구조
        Department organization = new Department("Organization");
        organization.addEmployee(engineering);
        organization.addEmployee(marketing);

        // 전체 조직의 이름과 총 급여 출력
        System.out.println("Organization Name: " + organization.getName());
        System.out.println("Total Salary: $" + organization.getSalary());
    }
}

위 예시에서는 개별 직원과 부서를 Employee 인터페이스로 표현하고, IndividualEmployee 클래스와 Department 클래스로 구현한다. Department 클래스는 여러 개의 Employee 객체(개별 직원 또는 다른 부서)를 포함할 수 있으며, getSalary() 메서드를 통해 부서 내 모든 직원의 총 급여를 계산한다.

 

[참고] https://www.geeksforgeeks.org/composite-design-pattern/

https://gyoogle.dev/blog/design-pattern/Composite%20Pattern.html