is this a valid interpretation of the composite pattern?
One recommendation I get out of the composite pattern is to provide default operations that handle inappropriate child management operations for a Leaf node (ie, throwing an exception on AddChild, returning an empty enumeration for Children, etc.).
My understanding of the classic pattern is to have a single abstract class with a Leaf subclass and开发者_JAVA技巧 a Composite subclass but if you provide default ops in the parent, doesn't it effectively obviate the need for the Leaf?
Does anyone do it this way?
Cheers,
Berrylit's possible we're talking about different things. i am assuming the composite pattern is as described on http://en.wikipedia.org/wiki/Composite_pattern
for that pattern, you would not expose operations that don't apply to the leaf node, like AddChild
(your example) because the Component
interface (using the names from the wikipedia article) is intended to expose only common actions that can be performed on either a leaf or a node. so there is no need for defaults.
there is an add()
on the Composite
class in the wikipedia article, but that is to add things to the composite "view", not to any particular data structure. in other words, you might access some parts of a tree of data through a composite interface, but the add()
method on the interface is adding or removing items from that collection, and not from the tree itself.
精彩评论