The composite pattern, as the name suggests, is used when composing objects into a complex structure that acts as one (refer to the following diagram). Internally, it is using data structures, such as trees, graphs, arrays, or linked lists to represent the model:
The JVM offers the best example of a composite pattern, since it is usually implemented as a stack machine (for portability reasons). Operations are pushed and popped from the current thread stack. For example, to calculate what 1 + 4 - 2 equals, it pushes 1, pushes 4, and executes add. The stack now has only value 5, pushes 2, and executes minus. Now the stack has only value 3, which is popped. The operation 1 + 4 + 2 - (reversed polish notation) can be easily modeled using the composite pattern, where each node is either a value, complex value, or an operand. Each node has a perform method that performs...