본문 바로가기
Swift

Swift에서 컴포지트 패턴(Composite Pattern)의 개념과 예제

by mr.conan 2023. 6. 15.
728x90
반응형

컴포지트 패턴(Composite Pattern)은 소프트웨어 개발에서 사용되는 디자인 패턴 중 하나입니다. Swift에서도 컴포지트 패턴을 활용하여 객체들을 트리 구조로 구성하고 일관된 방식으로 다룰 수 있습니다. 이 블로그 포스트에서는 컴포지트 패턴의 개념을 소개하고, Swift로 구현된 예제를 통해 컴포지트 패턴의 사용법을 알아보겠습니다.

 

컴포지트 패턴의 개념: 컴포지트 패턴은 객체들을 트리 구조로 구성하여 단일 객체와 복합 객체를 동일한 방식으로 취급할 수 있도록 합니다. 이를 통해 객체들의 계층 구조를 표현하고, 클라이언트는 단일 객체와 복합 객체를 구분하지 않고 일관된 방식으로 다룰 수 있습니다. 컴포지트 패턴은 객체 간의 계층적 관계를 표현할 때 유용합니다.

컴포지트 패턴 예제:

protocol Component {
    var name: String { get }
    func operation()
}

class Leaf: Component {
    let name: String

    init(name: String) {
        self.name = name
    }

    func operation() {
        print("Leaf \(name): Performing operation.")
    }
}

class Composite: Component {
    let name: String
    private var components: [Component] = []

    init(name: String) {
        self.name = name
    }

    func add(component: Component) {
        components.append(component)
    }

    func remove(component: Component) {
        components.removeAll { $0 === component }
    }

    func operation() {
        print("Composite \(name): Performing operation.")

        for component in components {
            component.operation()
        }
    }
}

위의 예제에서는 Component 프로토콜을 정의하고, Leaf 클래스가 이를 구현합니다. Leaf 클래스는 컴포지트 패턴에서의 단일 객체를 나타냅니다. Composite 클래스는 Component 프로토콜을 구현하며, 복합 객체를 나타냅니다. Composite 클래스는 여러 개의 Component를 관리하고, operation() 메서드를 호출할 때 하위 구성 요소들도 순회하며 작업을 수행합니다.

 

사용 예시:

let leafA = Leaf(name: "Leaf A")
let leafB = Leaf(name: "Leaf B")

let composite = Composite(name: "Composite")
composite.add(component: leafA)
composite.add(component: leafB)

composite.operation()

위의 예시에서는 Leaf 인스턴스인 leafAleafB를 생성하고, Composite 인스턴스인 composite에 추가합니다. 마지막으로 composite.operation()을 호출하여 복합 객체와 하위 구성 요소들의 작업을 수행합니다.

728x90
반응형