Skip to content

Instantly share code, notes, and snippets.

@linearhw
Last active December 27, 2017 06:14
Show Gist options
  • Save linearhw/00ecfd3023af2a194ab884df0b2ca8a0 to your computer and use it in GitHub Desktop.
Save linearhw/00ecfd3023af2a194ab884df0b2ca8a0 to your computer and use it in GitHub Desktop.

Composite

언제 사용하면 좋은가

  • 단일 객체든 객체들의 집합이든 같은 방법으로 취급해야 할 때
  • 기존 코드에서 단일 객체와 객체 집합을 동일한 방식/동일한 코드로 처리하고 있을 때

특징

  • 객체와 객체의 그룹을 구분 없이 하나의 인터페이스로 다룰 수 있게 한다
  • 트리 구조의 설계를 사용한다

예제

class File {
    private var name: String = ""
}

class Directory {
    private var name: String = ""
    private var children = [File]()
}

여기서, Directory 안에 여러 개의 Directory 가 있다는 걸 표현하려면?

수정 버전:

protocol Node {
    func getName() -> String
}

class File: Node {
    private var name: String = ""
    
    func getName() -> String {
        return name
    }
}

class Directory: Node {
    private var name: String = ""
    private var children: [Node] = []
    
    func getName() -> String {
        return name
    }
    
    func add(node: Node) {
        children.append(node)
    }
}

iOS usage

  • UIView

vs Decorator

공통점

  • 둘 다 여러 객체를 조직화하기 위해 쓰이는 기법인 만큼 구조는 비슷할 수 밖에 없다.
  • 그래서 Composite 패턴을 쓰다 보면 자연스럽게 Decorator 패턴을 쓰게 되는 경우도 있다.

차이점

  • 의도가 매우 다르다.
  • Composite gives an unified interface to a leaf and composite.
  • Decorator decorator gives additional feature to leaf, while giving unified interface.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment