Composite
JaninaVoigt (Talk | contribs) |
|||
Line 29: | Line 29: | ||
* Composite contains both Composite and leaf as Component. | * Composite contains both Composite and leaf as Component. | ||
* All Composites and leaves are seen as Component by Client. | * All Composites and leaves are seen as Component by Client. | ||
+ | |||
+ | ==Use When== | ||
+ | * You want to represent a hierarchy of parts and whole objects. | ||
+ | * You want clients to not know about whether they are dealing with a composition of objects or a single object. | ||
== Recognising the pattern == | == Recognising the pattern == |
Revision as of 06:59, 24 July 2009
The Composite pattern is useful whenever one has a class which may contain instances of itself. Common computer science examples are nodes in a tree structure, or shapes in a graphical model. More concrete physical world examples include regions (which can potentially contain many smaller regions), schools of fish (where those fish may swim, eat, etc in a collective fashion), and divisions/teams in a workplace.
The key feature of this pattern is a subclass which both extends the superclass, and contains (though an aggregation or composition relationship) a number of instances of the superclass.
The advantage gained from this structure is that we can transparently use a Composite Instance just as with a Primitive instance. shape.draw(), for example could draw any shape, from a primitive to a highly complex diagram or model.
Contents |
Features
Classes
- Interface (Abstract class) that represents Component.
- Concrete Composite class that implements Component.
- Concrete leaf class that implements Component.
- Client class.
Attribute
- Composite maintains a collection of Components. E.g, Collection<Component>
Methods
- Component has abstract methods to add and remove an Component to and from.
- Composite has concrete method to add an instance of Component that shared by Composites and leaves on the collection.
- Composite has concrete method to remove an instance of Component that shared by Composites and leaves from the collection.
Relationships
- Composite contains both Composite and leaf as Component.
- All Composites and leaves are seen as Component by Client.
Use When
- You want to represent a hierarchy of parts and whole objects.
- You want clients to not know about whether they are dealing with a composition of objects or a single object.
Recognising the pattern
Classes: Composite, Component, multiple Leaves
- Inheritance hierarchy that has a Component interface
- Component interface has declarations for add() and remove() methods for adding/removing Components.
- Composite class has private collection of Components.
See also
Design patterns | |
---|---|
Creational: Abstract Factory | Builder | Factory Method | Prototype | Singleton |