问题
I have question regarding composite pattern.
Is the base class "Component" act like a pointer to point leaf object in "Composite" class?
Edit: Let me ask my question in following words. "What is the relation between Composite and Component class?"
Here is the uml class diagram of the pattern.
回答1:
Relation between composite and component:
1) Leaf and Composite usually implement one interface or one abstract class. In your diagram they extend Component. So, the relation on your diagram is inheritance.
2) Composite contains instances of Component. Component, as it occasionally can be Composite, can also contain instances of Component. This is called recursive composition. In general, the relation is called aggregation.
回答2:
Component
- is the abstraction for all components, including composite ones
- declares the interface for objects in the composition
- (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate
Leaf
- represents leaf objects in the composition
- implements all Component methods
Composite
- represents a composite Component (component having children)
- implements methods to manipulate children
- implements all Component methods, generally by delegating them to its children
http://en.wikipedia.org/wiki/Composite_pattern
回答3:
All container and containee classes declare an “is a” relationship to the interface(Component).
All container classes declare a one-to-many “has a” relationship to the interface.
More here
来源:https://stackoverflow.com/questions/2434085/composite-pattern