-
Notifications
You must be signed in to change notification settings - Fork 0
Composite
Roberto Fronteddu edited this page Feb 9, 2023
·
5 revisions
The Composite is a Structural Design Pattern. The idea is to structure objects into tree structures and then work with them as if they were individual objects.
- We have a part-whole relationship hierarchy of objects and we want to be able to treat all objects in this hierarchy uniformly.
- Composites will delegate operations to their children while leaf nodes will implement functionalities.
-
Component:
- Defines interface used by the client.
- Defines behavior common to all classes, including methods to access children.
-
Leaf: Provides the implementation for the specified operations defined by the component.
-
Composite:
- Implements the Component interface and maintains a collection of children within it.
- When we call an operation through the Composite, the Composite delegate that operation to one of its children.
- The client doesn't know which leaf is executing an operation.
- Create an abstract class/interface for the Component
- The Component must declare all methods that are applicable to both leaf and composite.
- Choose who defines the children management operations, component or composite
- Implement the composite. An operation invoked doesn't the composite is propagated to all its children
- In the leaf nodes we have to handle the non-applicable operations like add/remove a child if they are defined in the component.
- The composite implementation will allow you to write algorithms without worrying about whether a node is a leaf or a composite.
- Composite uses composition
- Depending on the implementation, children management operations can be defined in the component or composite.
- Defining these operations on the component provides transparency but may force other leaves to implement unsupported methods.
- Defining them on the composite is safer but then the client needs to be made aware of the composite. This second approach makes it easier to provide default behavior.
- Overall, the client code is simpler when the children management operations are defined in the component.
- You can provide a method to access the parent of a node to simplify tree traversal.
- Deals with a tree structure of objects.
- Leaf nodes and composites have the same interface and composites delegate operations to children.
- Contains another single object.
- Decorators add or modify the behavior of the contained object and do not have a notion of children.
- Difficult to restrict what gets added to the hierarchy, when the number of types of leaf increases, clients are forced to write lots of runtime checks to ensure that operations are available on a node.
- Complex process to implement the hierarchy.
- Generally used in UI frameworks
- UIViewRoot in JSF provides a common UIComponent interface,