Applied Design Patterns with Java

Structural :: Composite (163) {C ch 11}

Intent
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Motivation

Graphics applications like drawing editors let users build complex diagrams out of simple components. The user can group components to form larger components, which in turn can be grouped to form still larger components. A simple implementation could define classes for graphical primitives such as Text and Lines plus other classes that act as containers for these primitives. But, code that uses these classes must treat primitive and container objects differently, even if the time the user treats them identically. The need to distinguish these objects makes the application more complex. The Composite pattern describes how to use recursive composition so that clients don't have to make this distinction.


The key to the
Composite pattern is an abstract class that represents both primitives and their containers, named is Graphic. Graphic has operations like Draw() that are specific to graphical objects, plus operations that all Composite objects share, for accessing and managing its children. The subclasses Line, Rectangle, and Text define primitive graphic objects. These classes implement Draw() to draw lines, rectangles, and text. As primitive graphics have no child graphics, none of these subclasses implements child-related operations.

The
Picture class defines an aggregate of Graphic objects. Picture implements Draw() to call Draw() on its children, and it implements child-related operations accordingly. Because the Picture interface conforms to the Graphic interface, Picture objects can compose other Pictures recursively. The following diagram shows a Composite object structure of recursively composed Graphic objects:


Catalog Structural Prev Next