- An Implementation of a Composite
- The Employee Classes
- Building the Employee Tree
- Self-Promotion
- Consequences of the Composite Pattern
- Other Implementation Issues
Consequences of the Composite Pattern
The Composite pattern allows you to define a class hierarchy of simple objects and more complex composite objects so they appear to be the same to the client program. Because of this simplicity, the client can be that much simpler, since nodes and leaves are handled in the same way.
The Composite pattern also makes it easy for you to add new kinds of components to your collection as long as they support a similar programming interface. On the other hand, this has the disadvantage of making your system overly general. You might find it harder to restrict certain classes where this would normally be desirable.
A Simple Composite
The intent of the Composite pattern is to allow you to construct a tree of various related classes, even though some have different properties than others and some are leaves that do not have children. However, for very simple cases, you can sometimes use just a single class that exhibits both parent and leaf behavior. In the SimpleComposite example, we create an Employee class that always contains the ArrayList subordinates. This collection of employees will either be empty or populated, and this determines the nature of the values that you return from the getChild and remove methods. In this simple case, we do not raise errors and always allow leaf nodes to be promoted to have child nodes. In other words, we always allow execution of the add method.
While you may not regard this automatic promotion as a disadvantage, in systems where there are a very large number of leaves, it is wasteful to keep a Collection initialized and unused in each leaf node. In cases where there are relatively few leaf nodes, this is not a serious problem.
Composites in .NET
In .NET, you will note that the Node object class we use to populate the TreeView is in fact just such a simple Composite pattern. You will also find that the Composite describes the hierarchy of Form, Frame, and Controls in any user interface program. Similarly, toolbars are containers, and each may contain any number of other containers.
Any container may then contain components such as buttons, check boxes, and TextBoxes, each of which is a leaf node that cannot have further children. They may also contain ListBoxes and grids that may be treated as leaf nodes or that may contain further graphical components. You can walk down the Composite tree using the Controls collection.