Composite pattern comes under Structural design pattern.
It composes objects into tree structures to represent part-whole hierarchies.
Nodes of tree structure are accessed uniformly irrespective of whether its
a leaf nodes or branch (composite) node.
Behaviour & Advantages
Treats compositions and individual objects in a similar manner.
It forms a kind of one to many relationship where the container node
has relation to one or more child nodes. The child node may be a container node or leave node.
A branch with no children is treated as leave node and each branch ends with leave nodes.
Participants
Component
Abstract interface for all components (both Composite and Leave components).
Declares an interface for accessing the elements of composition (child components)
and optionally parent component.
Leaf
It has no children and represents leave objects in the composition.
Composite
It acts as a container for child components and holds a reference.
The child component can be a Composite or Leaf component.
Client
One who operates on composite structure through the Component interface.
This example shows programming knowledge categorized in a tree hierarchy.
Here IKnowledge interface acts as Component, Topic class acts as Leaf
and TopicContainer acts as Composite components.
public class TopicContainer extends Topic implements IKnowledge {
public TopicContainer(String topicName) { super(topicName);
}
/**
* Provide an interface to add sub topics.
*/ public void addSubTopic(IKnowledge subTopic) {
subTopic.setParentTopic(this); this.subTopics.add(subTopic);
}