| |||||||||
computer programming, composite pattern is one of the design patterns to decompose objects into their parts, and reassemble them in whichever combination one needs with "has-a" relationships. That is to say, to break things into the largest parts that still allow reuse of the parts, and build objects of those.
The other definition is to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
When: Any time there is partial overlap in the capabilities of objects.
Objects may be members of a number of linked lists in our system. The linked lists organize the objects by different criteria.
This can be inherited, but inheriting it multiple times doesn't do any good: one only ever has one instance of the LinkedList this way - oneself. Using composition gives the desired result:
"Method A" and "method B" illustrate two very different approaches to giving users of the object access to the parts. "Method A" creates all new accessors which do their work by calling accessors in the composing objects. "Method B" simply returns the composing objects and lets the user call the methods directly. For example:
Which method is preferable varies. If the object is merely a container for other objects, B makes more sense. If the object is a Facade, providing a new interface to several objects, A makes more sense. If the contained objects are considered to be implementation dependent, and having to support returning intermediate objects in the future is not desirable, A allows better hiding of theimplementation. B makes for shorter code and less typing when the relationship between the objects is not likely to change.
Each LinkedList instance is a "delegate" in this example. The methods that propagate requests to them are "delegate methods".
Compose means a special thing: it refers to building objects using DelegationConcept. Delegation-composition hangs onto constituent parts-using references. By contrast, MixIns inherit from each part. MixIns prevent returning a WholeObject in response to requests for information, and they prevent having more than one of any given part.
The article is originally from the Perl Design Patterns Book