“Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.”
Design Patterns: Elements of Reusable Object-Oriented Software
A Composite is something really simple and straightforward, with countless examples in the computing world (at least I found quite many examples for it). You can easily imagine it as a tree structure: a node can be a composite, or a leaf. Composites can contain further composites and/or leaves, and so forth.
The big advantage in this pattern is that it lets you treat primitive and container objects in the same manner, thus simplifying your code. Now let’s understand the key players here:
- Component: defines the interface for the objects of the composition, their default behavior, the method to get or set the child components.
- Leaf: primitives of the composition which haven’t got child objects.
- Composite: components that have child objects, defining their own child-management methods.
- Client: works with composition through the component interface.
An example is the View object in the Cocoa Touch Framework (to get a bit further from the .NET Framework). Each View can have further Views which can be accessed through the parent View. But here’s a .NET sample:
abstract class View
virtual void Add(View);
virtual Void Remove(View);
virtual IEnumerable<View> Children;
private string Name;
public View (string _name);
Name = _name;
class ButtonView: View
The code sample above defines some common functionality of the View class like adding and removing, and even enumerating children objects. We’ve subclassed it with another class responsible for uilding button objects on the screen, with the ability of storing further View objects. Maybe it’s not your first thought regarding the code, but it’s a quite useful structure we’ve outlined above.
Design Patterns (book): pp 163 – 173