Composite Design Pattern
Structural pattern. Structural design patterns are concerned with composing classes and objects into larger structures.
Intent: "Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly." [GoF]
Open in the interactive referenceDownload the PDF reference
Intent
The intent of the Composite design pattern is to:
"Compose objects into
tree structures to represent part-whole
hierarchies.
Composite lets clients treat individual objects and
compositions of objects uniformly."
[GoF]
See Problem and Solution
sections for a more structured description of the intent.
-
The Composite design pattern solves problems like:
-
How can a part-whole hierarchy be represented
so that clients can treat individual objects and compositions of objects uniformly?
-
How can a part-whole hierarchy be represented
- Tree structures are widely used in object-oriented systems to represent hierarchical object structures like part-whole hierarchies.
-
A tree structure consists of individual
(
Leaf) objects and subtree (Composite) objects.
ACompositeobject has children, that is,Leafobjects or other (lower-level)Compositeobjects. [BGI] -
The Composite pattern describes how to solve such
problems:
- Compose objects into tree structures to represent part-whole hierarchies.
-
Define separate
Compositeobjects that compose the objects in a part-whole hierarchy into tree structures. -
Clients work through a common
Componentinterface to treatLeafandCompositeobjects uniformly, which greatly simplifies clients and makes them easier to implement, change, test, and reuse.
Background Information
-
"A tree is a data structure composed of a set of nodes
organized into a hierarchy.
Each node has a parent and an ordered list of
zero, one, or multiple children.
The children can be simple nodes or complete subtrees.
In computer science, we draw trees with the root node at the top and the branches descending below. Root nodes are analogous to the root directory on a disk. Children are analogous to files and subdirectories." [TP07, (2) p75]
Problem
The Composite design pattern solves
problems like:
How can a part-whole hierarchy be represented
so that clients can treat individual objects
and compositions of objects uniformly?
See Applicability section for all problems Composite can solve.
See Solution section for how Composite solves the problems.
-
An inflexible way to represent a part-whole hierarchy is to define
(1)
Partobjects and (2)Wholeobjects that act as containers forPartobjects.
Clients of the hierarchy must treatPartandWholeobjects differently, which makes them more complex especially if the object structure is constructed and traversed dynamically. - That's the kind of approach to avoid if we want to simplify client code so that all objects in the hierarchy can be treated uniformly.
-
For example, representing Bill of Materials.
A Bill of Materials (BOM) is a part-whole structure that describes the parts and subcomponents (wholes) that make up a manufactured product (see also Builder for creating a BOM).
It should be possible, for example, to calculate the total price either of an individual part or a complete subcomponent without having to treat part and subcomponent differently (see Sample Code / Example 2 / BOM). -
For example, representing text documents.
A text document can be organized as part-whole hierarchy consisting of characters, pictures, etc. (parts) and lines, pages, etc. (wholes).
It should be possible, for example, to treat displaying a particular page or the entire document uniformly.
Solution
The Composite design pattern provides a solution:
Define separate
Composite objects
that compose
the objects of a part-whole hierarchy
into a tree structure.
Work through a common Component interface
to treat Leaf
and
Composite objects uniformly.
Describing the Composite design in more detail is the
theme of the following sections.
See Applicability section for all problems Composite can solve.
-
The key concept in this pattern
is to compose
Leafobjects andCompositeobjects if any into higher-levelCompositeobjects recursively (recursive composition). [BGI] The resulting structure is a tree structure that represents a part-whole hierarchy. -
Define separate
Compositeobjects:
-
Define a class (
Composite) that maintains a container of childComponentobjects (children) and forwards requests to these children (for each child in children: child.operation()). - For implementing child-related operations (like adding or removing child components to or from the container) see Implementation.
-
Define a class (
-
"The key to the Composite pattern is an abstract class
[
Component] that represents both primitives and their containers." [GoF, p163] [BGI]-
Clients can treat
Leafobjects and entireCompositeobject structures uniformly (that is, clients do not know whether they are working withLeaforCompositeobjects): -
If the receiver of a request is a
Leaf, the request is performed directly.
If the receiver is aComposite, the request is performed on allComponentobjects downwards the hierarchy. - This greatly simplifies clients of complex hierarchies and makes them easier to implement, change, test, and reuse.
-
Clients can treat
Background Information
-
Recursive Composition
For example, compose bottom-level leaf objects (leaf3,leaf4,leaf5) into a composite object (composite2), compose this composite object and same-level leaf objects (leaf1,leaf2) into a higher-level composite object (composite1), and so on recursively (see the above Sample Object Collaboration).
The resulting structure is a tree structure that represents a part-whole hierarchy.
Motivation
Consider the left design (problem):
-
No common interface / direct access.
Complicated clients.-
No common interface is defined
for individual objects
(
Part) and their containers (Whole). -
This forces clients to treat
PartandWholeobjects differently, which greatly complicates client code for constructing and traversing complex hierarchies.
-
No common interface is defined
for individual objects
(
Consider the right design (solution):
-
Working through a common interface.
Simplified clients.-
A common interface
(
Component) is defined for individual objects (Leaf) and their containers (Composite). -
This lets clients treat
LeafandCompositeobjects uniformly, which greatly simplifies client code for constructing and traversing complex hierarchies.
-
A common interface
(
Applicability
Design Problems
-
Representing Part-Whole Hierarchies
-
How can a part-whole hierarchy be represented
so that clients can treat individual objects and compositions of objects uniformly? -
How can a part-whole hierarchy be represented
so that clients can treat the hierarchy as single object? - How can a part-whole hierarchy be represented as tree structure?
-
How can a part-whole hierarchy be represented
Structure
Static Class Structure
-
Client-
Refers to the
Componentinterface.
-
Refers to the
-
Component-
Defines a common interface for
LeafandCompositeobjects.
-
Defines a common interface for
-
Leaf- Defines individual objects that get composed.
-
Composite-
Maintains a container of child
Componentobjects (children). -
Forwards requests
to these children
(
for each child in children: child.operation()).
-
Maintains a container of child
Dynamic Object Collaboration
-
In this sample scenario,
a
Clientobject sends a request to the top-levelCompositeobject in the hierarchy. -
The request is forwarded to the
child
Componentobjects (lower-levelLeafandCompositeobjects) recursively, that is, the request is performed on all objects downwards the hierarchy. -
A
Compositeobject may do work of its own before and/or after forwarding a request, for example, to compute total prices (see Sample Code / Example 2). -
See also Sample Code / Example 1.
Consequences
Advantages (+)
-
Simplifies clients.
- Clients can treat all objects in the hierarchy uniformly, which greatly simplifies client code.
-
Makes adding new components easy.
-
Clients refer to the common
Componentinterface and are independent of its implementation. -
That means, clients do not have to be changed when new
CompositeorLeafclasses are added or existing ones are extended.
-
Clients refer to the common
-
Allows building and changing complex hierarchies
dynamically at run-time.
- The pattern shows how to apply recursive composition to build complex hierarchical object structures dynamically at run-time.
Disadvantages (–)
-
Uniformity versus type safety.
- There are two main design variants to implement child-related operations: design for uniformity and design for type safety (see Implementation).
- The Composite pattern emphasizes uniformity over type safety.
Implementation
Implementation Issues
Implementing Child-Related OperationsAdding a child component to the container (
add(child)),
removing a child component from the container (remove(child)),
and accessing a child component (getChild()).
Variant 1: Design for Uniformity
-
The only way to provide uniformity
is to define child-related operations
in the
Componentinterface. -
This enables uniformity because
clients can treat
LeafandCompositeobjects uniformly. -
But we loose type safety because
LeafandCompositeinterfaces (types) are not cleanly separated. -
The abstract
Componentclass implements default behavior for child-related operations like "do nothing" or "throw an exception". TheLeafclass inherits the default implementations, andCompositemust redefine them. - Uniformity is useful for dynamic structures because clients often need to perform child-related operations (in a document editor, for example, where the object structure is dynamically created and changed each time a document is changed).
- The Composite design pattern emphasizes uniformity over type safety.
Variant 2: Design for Type Safety
-
The only way to provide type safety is to define
child-related operations
solely in the
Compositeclass. -
This enables type safety because
we can rely on the type system to enforce type constraints
(for example, that clients can not perform child-related operations
on
Leafcomponents). -
But we loose uniformity because
clients must treat
LeafandCompositeobjects differently. - Type safety is useful for static structures (that do not change very often) because most clients do not need to perform child-related operations.
Sample Code 1
Basic Java code for implementing the sample UML diagrams.
1 package com.sample.composite.basic;
2 public class Client {
3 // Running the Client class as application.
4 public static void main(String[] args) {
5 // Building a tree structure.
6 Component composite2 = new Composite("composite2 ");
7 composite2.add(new Leaf("leaf3 "));
8 composite2.add(new Leaf("leaf4 "));
9 composite2.add(new Leaf("leaf5 "));
10 Component composite1 = new Composite("composite1 ");
11 composite1.add(new Leaf("leaf1 "));
12 composite1.add(composite2);
13 composite1.add(new Leaf("leaf2 "));
14
15 // Performing an operation on composite1
16 // (walking down the entire hierarchy).
17 System.out.println("(1) " + composite1.operation());
18
19 // Performing an operation on composite2
20 //(walking down the subtree).
21 System.out.println("(2) " + composite2.operation());
22
23 }
24 }
(1) composite1 leaf1 composite2 leaf3 leaf4 leaf5 leaf2
(2) composite2 leaf3 leaf4 leaf5
1 package com.sample.composite.basic;
2 import java.util.Collections;
3 import java.util.Iterator;
4 public abstract class Component {
5 private String name;
6 public Component(String name) {
7 this.name = name;
8 }
9 public abstract String operation();
10
11 public String getName() {
12 return name;
13 }
14 // Default implementation for child management operations.
15 public boolean add(Component child) { // fail by default
16 return false;
17 }
18 public Iterator<Component> iterator() { // null iterator
19 return Collections.<Component>emptyIterator();
20 }
21 }
1 package com.sample.composite.basic;
2 public class Leaf extends Component {
3 public Leaf(String name) {
4 super(name);
5 }
6 public String operation() {
7 return getName();
8 }
9 }
1 package com.sample.composite.basic;
2 import java.util.*;
3 public class Composite extends Component {
4 private List<Component> children = new ArrayList<Component>();
5
6 public Composite(String name) {
7 super(name);
8 }
9 public String operation() {
10 Iterator<Component> it = children.iterator();
11 String str = getName();
12 Component child;
13 while (it.hasNext()) {
14 child = it.next();
15 str += child.operation();
16 }
17 return str;
18 }
19 // Overriding the default implementation.
20 @Override
21 public boolean add(Component child) {
22 return children.add(child);
23 }
24 @Override
25 public Iterator<Component> iterator() {
26 return children.iterator();
27 }
28 }
Sample Code 2
BOM Bill of Materials / Representing the BOM as tree/composite structure.
Calculating total prices (getPrice()) for composite components
(Chassis and Mainboard).See also Visitor design pattern, Sample Code / Example 2 (pricing visitor).
1 package com.sample.composite.bom;
2 public class Client {
3 // Running the Client class as application.
4 public static void main(String[] args) throws Exception {
5 // Building the tree/composite structure.
6 Component mainboard = new Mainboard("Mainboard", 100);
7 mainboard.add(new Processor("Processor", 100));
8 mainboard.add(new Memory("Memory ", 100));
9 Component chassis = new Chassis("Chassis ", 100);
10 chassis.add(mainboard);
11 chassis.add(new Disk("Disk ", 100));
12 //
13 // Clients can treat the hierarchy as a single object.
14 // If the receiver is a leaf,
15 // the request is performed directly.
16 // If the receiver is a composite,
17 // the request is forwarded to its child components recursively.
18 //
19 System.out.println(chassis.getName() + " total price: " +
20 chassis.getPrice());
21 //
22 System.out.println(mainboard.getName() + " total price: " +
23 mainboard.getPrice());
24 }
25 }
Chassis total price: 500
Mainboard total price: 300
1 package com.sample.composite.bom;
2 import java.util.Collections;
3 import java.util.Iterator;
4 public abstract class Component {
5 private String name;
6 private long price;
7 public Component(String name, long price) {
8 this.name = name;
9 this.price = price;
10 }
11 public String getName() {
12 return name;
13 }
14 public long getPrice() { // in cents
15 return price;
16 }
17 // Defining default implementation for child management operations.
18 public boolean add(Component c) { // fail by default
19 return false;
20 }
21 public Iterator<Component> iterator() {
22 return Collections.emptyIterator(); // null iterator
23 }
24 public int getChildCount() {
25 return 0;
26 }
27 }
1 package com.sample.composite.bom;
2 import java.util.ArrayList;
3 import java.util.Iterator;
4 import java.util.List;
5 public class CompositeComponent extends Component {
6 private List<Component> children = new ArrayList<Component>();
7 public CompositeComponent(String name, long price) {
8 super(name, price);
9 }
10 // Overriding the default implementation.
11 @Override
12 public long getPrice() {
13 long sum = super.getPrice();
14 for (Component child : children) {
15 sum += child.getPrice();
16 }
17 return sum;
18 }
19 @Override
20 public boolean add(Component child) {
21 return children.add(child);
22 }
23 @Override
24 public Iterator<Component> iterator() {
25 return children.iterator();
26 }
27 @Override
28 public int getChildCount() {
29 return children.size();
30 }
31 }
1 package com.sample.composite.bom;
2 public class Chassis extends CompositeComponent { // Composite
3 public Chassis(String name, long price) {
4 super(name, price);
5 }
6 }
1 package com.sample.composite.bom;
2 public class Mainboard extends CompositeComponent { // Composite
3 public Mainboard(String name, long price) {
4 super(name, price);
5 }
6 }
1 package com.sample.composite.bom;
2 public class Processor extends Component { // Leaf
3 public Processor(String name, long price) {
4 super(name, price);
5 }
6 }
1 package com.sample.composite.bom;
2 public class Memory extends Component { // Leaf
3 public Memory(String name, long price) {
4 super(name, price);
5 }
6 }
1 package com.sample.composite.bom;
2 public class Disk extends Component { // Leaf
3 public Disk(String name, long price) {
4 super(name, price);
5 }
6 }