Applied Design Patterns with Java
Structural :: Composite (163) {C ch 11}
Collaborations
- Clients use the Component class interface to interact
with objects in the Composite structure. If the recipient is a Leaf, then the request is handled
directly. If the recipient is a Composite, then it forwards requests to its child components, for performing
additional operations before and/or after forwarding.
Consequences
The Composite pattern has the following consequences:
- Defines class hierarchies of primitive objects and Composite
objects.
Primitive objects can be composed into more complex objects, which can be composed recursively. Wherever client
code expects a primitive object, it can also take a Composite object.
- Makes the client simple. Clients can treat Composite structures and individual objects uniformly. Clients shouldn't
know or care if they're dealing with a leaf or a Composite component. This simplifies client code, because it avoids having
to write tag-and-case-statement-style functions over the classes that define the composition.
- Makes it easier to add new kinds of components. Newly defined Composite or Leaf subclasses work automatically with existing structures and client code.
Clients don't have to be changed for new Component classes.
- Can make a design overly general. The disadvantage of making it easy to add new components is that it makes it harder to
restrict the components of a Composite. The type system can't enforce those constraints. Run-time checks are used instead.
Catalog Structural Prev Next