The Composite Pattern
Defined
The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uni-formally.The Composite Pattern allows use to build structures of objects in the form of trees that contain both compositions of objects and individual objects as nodes.
Using a composite structure, we can apply the same operations over both composites and individual objects, in other words, in most cases we can ignore the difference between compositions of objects and individual objects.
Lets think about composition in terms of menus: this pattern gives us a way to create a tree structure that can handle a nested group of menus and menu items in the same structure. By putting menus and items in the same structure we create a part-whole hierarchy; that is, a tree of objects that made of parts(menus and menu items) but that can be treated as a whole, like on big uber menu.
Once we have our uber menu, we can use this pattern to treat "individual objects and compositions uniformly".
What does that mean? it means if we have a tree structure of menus, sub menus, and perhaps subsubmenus with menu items, then any menu is a "composition" because it can constrains both other menus and menu items, The individual objects are just the menu items, they don't hold other objects,
A composite contains components, components come in two flavors: composites and leaf elements A composite holds a set of children, those children may be other composites or leaf elements.
Diagrams
Tree Structure
Pattern Structure
Diagram shows example how we can tree like structure, where a menu can compose of menu items, and other menus that can contain their own menu items or menus.
Code Example
Bullet Points
- The Composite Pattern provides a structure to hold both individual objects and composites.
- The Composite Pattern allows clients to treat composites and individual objects uniformly.
- A Component is any object in a Composite structure. Components may be other composites or leaf nodes.
- There are many design trade offs in implementing Composite. You need to balance transparency and safety with your needs.
No comments:
Post a Comment