Friday, April 20, 2007

Composite

The Composite pattern is to build a class hiararchy such that each subclasses of it can be treated likewise, no matter it is a single object or a collection of objects. The following figure presents us the main idea:

In the figure, the Leaf subclass is the basic element that can build a Composite object. To implement a common operation to both the Leaf object and the Composite one, it is required that Leaf must implement the operation and Composite can forward the request to its childrens (perhaps a Leaf or a Composite one).

The Leaf class doesn't really need an Add() or Remove() operation, and hence can throw exceptions in these functions. In order to traverse the Composite object more easily, each Component can maintain a pointer to its parent. The children of a Composite object should be destroyed by the object itself in its destructor function by forwarding the request to all its children.

No comments: