-
Book Overview & Buying
-
Table Of Contents
TypeScript 5 Design Patterns and Best Practices - Second Edition
By :
The Composite pattern is a structural design pattern that allows you to define trees of objects that belong to the same hierarchy.
The core idea is to create a common interface for both simple (leaf) objects and complex (composite) objects that may contain other objects. This unified interface allows us to handle both types consistently.
A common real-world analogy for the Composite pattern is a filesystem, where directories (composite objects) can contain both files (leaf objects) and other directories (composite objects). Both files and directories share a common interface, allowing clients to interact with them uniformly. For example, you can perform operations such as calculating the total size of a directory or listing its contents without needing to differentiate between files and subdirectories.
Consider using the Composite pattern in the following instances: