GofPatterns Gofpatterns





Structural Patterns  «Prev  Next»

Composite Pattern

The Composite pattern enables you to create hierarchical tree structures of varying complexity, while allowing every element in the structure to operate with a uniform interface. The Composite pattern combines objects into tree structures to represent either the whole hierarchy or a part of the hierarchy. This means the Composite pattern allows clients to treat individual objects and compositions of objects uniformly. The figure below illustrates the Composite pattern.
Furthermore, the composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.
Motivation
When dealing with Tree-structured data, programmers often have to discriminate between a leaf-node and a branch. The solution is an interface that allows treating complex and primitive objects uniformly. In object-oriented programming, a composite is an object designed as a composition of one-or-more similar objects, all exhibiting similar functionality.
This is known as a "has-a" relationship between objects. The key concept is that you can manipulate a single instance of the object just as you would manipulate a group of them. The operations you can perform on all the composite objects often have a least common denominator relationship. For example, if defining a system to portray grouped shapes on a screen, it would be useful to define resizing a group of shapes to have the same effect (in some sense) as resizing a single shape.


Composite Pattern
Composite Pattern in Java
Benefits:
The following lists the benefits of using the Composite pattern:
  1. Defines class hierarchies consisting of primitive objects and composite objects
  2. Makes it easier to add new kinds of components
  3. Provides flexibility of structure and a manageable interface
When to use:
You should use the Composite pattern when:
  1. You want to represent the whole hierarchy or part of the hierarchy of objects.
  2. You want clients to be able to ignore the difference between compositions of objects and individual objects.
  3. The structure can have any level of complexity, and is dynamic.