Composite cho phép compose objects thành tree structures để biểu diễn part-whole hierarchies — client xử lý individual objects và compositions đồng nhất qua cùng một interface.
Ví dụ: file system:
typescript
interface FileSystemItem {
getSize(): number
}
class File implements FileSystemItem {
constructor(private size: number) {}
getSize() { return this.size }
}
class Folder implements FileSystemItem {
private children: FileSystemItem[] = []
add(item: FileSystemItem) { this.children.push(item) }
getSize() {
return this.children.reduce((sum, c) => sum + c.getSize(), 0)
}
}Client gọi getSize() trên cả File và Folder mà không cần biết loại.
- Trong React, component tree là ứng dụng tự nhiên của Composite — component con và cha đều là React component.
- Dùng khi: cần biểu diễn tree hierarchy; khi muốn client treat leaf và composite đồng nhất.
- Không dùng khi: hierarchy phẳng hoặc interface chung quá generic, khó type-safe.
Composite lets you compose objects into tree structures to represent part-whole hierarchies — clients treat individual objects and compositions uniformly through a single interface.
Example: a file system:
typescript
interface FileSystemItem {
getSize(): number
}
class File implements FileSystemItem {
constructor(private size: number) {}
getSize() { return this.size }
}
class Folder implements FileSystemItem {
private children: FileSystemItem[] = []
add(item: FileSystemItem) { this.children.push(item) }
getSize() {
return this.children.reduce((sum, c) => sum + c.getSize(), 0)
}
}The client calls getSize() on both files and folders without needing to know the type.
- In React, the component tree is a natural application of Composite — leaf and parent components are both React components.
- Use it when you need to represent a tree hierarchy or when you want clients to treat leaves and composites uniformly.
- Avoid it when the hierarchy is flat or when a shared interface is too generic to be type-safe.