[swift] Composite 디자인 패턴
Composite 디자인 패턴은 객체들을 트리 구조로 구성하여 계층 구조를 표현할 때 유용한 디자인 패턴입니다. 이 패턴은 개별 객체와 객체 그룹을 동일한 방식으로 취급할 수 있도록 합니다.
언제 유용한가요?
Composite 패턴은 다음과 같은 경우에 사용될 수 있습니다.
- 객체와 객체들의 계층 구조를 표현하고자 할 때
- 개별 객체를 묶어서 복합 객체로 다루고자 할 때
- 일관된 방법으로 개별 객체와 복합 객체를 다루고자 할 때
어떻게 구현하나요?
Composite 패턴을 구현하기 위해 다음과 같은 구성 요소들을 사용합니다.
- Component: 복합 객체와 개별 객체를 위한 인터페이스를 정의합니다.
- Leaf: 개별 객체를 나타내는 클래스로서 Component 인터페이스를 구현합니다.
- Composite: 복합 객체를 나타내는 클래스로서 Leaf와 다른 Composite 객체들을 자식으로 가질 수 있습니다.
예제 코드
protocol Component {
func operation()
}
class Leaf: Component {
func operation() {
print("Leaf operation")
}
}
class Composite: Component {
private var children: [Component] = []
func add(component: Component) {
children.append(component)
}
func operation() {
print("Composite operation")
for child in children {
child.operation()
}
}
}
// 사용 예
let leaf1 = Leaf()
let leaf2 = Leaf()
let composite = Composite()
composite.add(component: leaf1)
composite.add(component: leaf2)
composite.operation()
위의 예제 코드는 Swift로 Composite 패턴을 구현한 것입니다. Leaf와 Composite 클래스는 Component 프로토콜을 구현하여 동일한 방식으로 다룰 수 있도록 합니다.
정리
Composite 디자인 패턴을 사용하면 복합 객체와 개별 객체를 일관된 방식으로 다룰 수 있으며, 객체들의 계층 구조를 표현하기에 유용합니다. 이를 통해 객체들 간의 관계를 표현하거나 복합 객체를 구성하는 방법을 추상화할 수 있습니다.
참고 자료
- Wikipedia - Composite pattern
- Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides
- Swift Design Patterns by Paul Hudson
- Composite Pattern in Swift