Composites

Problem

An IDE (JDeveloper, Eclipse, NetBeans, etc.) maintains an internal representation of a project.

A project contains packages.

A package contains classes and sub-packages. A sub-package contains classes and sub-sub-packages, and so on.

Of course there is no important distinction between a package, sub-package and sub-sub-package.

If the IDE represents package, sub-package, and sub-sub-package as different classes, where will it end? The IDE will have to limit the depth of the package structure of a project.

Solution

There is no reason why a collection object (like a package) can't be recursive and contain other collection objects like itself:

If a collection can contain other collections as well as some other type of non-collection element, then we must introduce an abstract base class for both types of elements:

This The Composite pattern.

Here's how to apply it to our problem:

Here's a general template for the composite pattern:

Composite.java

References

The Composite pattern