Q-1). What problem does the Composite Pattern solve?
A-1). It simplifies client code by allowing uniform treatment of individual and composite objects.
Q-2). Where is the Composite Pattern used in real life?
A-2). File Explorer (folders and files), GUI menus.
Q-3). How does the Composite Pattern violate the Liskov Substitution Principle (LSP)?
A-3). If leaves and composites do not behave uniformly for some operations, LSP is violated. E.g., add() might be supported in composite but not in leaves.
Q-4). How do you ensure the composite doesn’t contain itself recursively?
A-4). By adding runtime checks to prevent circular references.
Q-5). How does the Composite Pattern support the open/closed principle?
A-5). New leaf or composite classes can be added without changing existing code, making it open for extension and closed for modification.
Q-6). How would you handle type-specific operations on only leaves or only composites?
A-6). Use the Visitor Pattern to separate operations from structure.
Q-7). How do you implement rollback or transactional operations in a composite structure?
A-7). Use a Command or Memento pattern alongside the composite to support undo/redo by tracking state at each node level.
Q-8). What are the trade-offs between the Composite and Decorator patterns?
A-8). The difference between the Composite and Decorator patterns is as follows:
| Composite | Decorator |
| Composite is for hierarchical trees of objects | Decorator is for dynamically adding responsibilities |
| Composite focuses on structure | Decorator focuses on behavior |