Composite Design Pattern

Up Java Resources

    This is an abstraction model that allows a client to treat individual objects and compositions of objects uniformly. It allows you to build complex objects by recursively composing similar objects in a tree-like manner. It also allows the objects in the tree to be manipulated in a consistent manner, by requiring all of the objects in the tree to have a common superclass or interface.

    The motivation comes from the natural need to build complex things from simpler things. And then build even more complex things based on what you have already build and so on ... But you would like to treat all of them the same way.

    How you do it? You create an abstract component, AbstractComponent, that declares the interface for objects to be composed. It also implements default behavior common to all classes. You also have a Composite or AbstractComposite class that has no specific behavior itself. When the operation() is invoked it is simply sequentailly sent to all its children. The Composite class implements child-related operations. And of course you have the ConcreteComponent classes.

    Here is a slightly different design

    So the sytsem works like that: the client uses the Component class to put a request; if the recipient is a ConcreteComponet it handles the request immediately; if the recipient is a CompositeComponent it forwards the request down to its children and the request will eventually be serviced.

    Some implementation issues:

    • Explicit parent references (related to the "Chain of responsibility" pattern).
    • What to put in the Component interface?
    • Child ordering

    What do we achieve using the Composite design pattern? We can build complex components organized in tree-like hierarchies that can be treated uniformly by the Client. Thus we can make the client simpler. Our design is more general and it is easy to add new kinds of Components without touching the general structure or the Client. It also allows us to create arbitrarily complex behaviors with a minimum effort spent (see BallWorld).

    Written by Demetrios Demopoulos. 2/22/02