Composite Pattern
Bryan Hansen
twitter: bh5k | [Link]
Concepts
▪ Components represent part or whole structure
▪ Compose objects into tree structures
▪ Individual object treated as a Composite
▪ Same operations applied on individual and
composites
▪ Examples:
▪ [Link]
▪ JSF widgets
▪ RESTful service GETs
Design
Tree structured
Component
Leaf or Composite, same operations
Composite knows about child objects
Component, Leaf, Composite
UML
Everyday Example - Map
Map<String, String> personAttributes = new HashMap<>();
[Link]("site_role", “person");
[Link]("access_role", "limited");
Map<String, String> groupAttributes = new HashMap<>();
[Link]("group_role", "claims");
Map<String, String> secAttributes = new HashMap<>();
[Link](personAttributes);
[Link](groupAttributes);
Exercise Composite
Menu, MenuItem, MenuComponent
Create Composite
Features Not Supported
Pitfalls
▪ Can overly simplify system
▪ Difficult to restrict
▪ Implementation can possibly be costly
Contrast
Composite Decorator
▪ Tree structure ▪ Contains another entity
▪ Leaf and Composite have same ▪ Modifies behavior (adds)
interface ▪ Doesn’t change underlying object
▪ Unity between objects
Composite Summary
• Generalizes a hierarchical structure
• Can simplify things too much
• Easier for clients
• Composite != Composition