The composite structural pattern allows you to build elaborate objects from smaller objects and not worry about how big they get. You can treat your composite objects as if they are all the same.

If you have hierarchical data, then consider this design pattern as a way to help you work with objects that represent roots of the hierarchy without worrying about if there is just a single item in the hierarchy or thousands.

You start out with an abstract class that allows you to treat all the classes participating in this pattern the same. We’ll call this class a Component. Then let’s say you want to represent a file system with files and folders. All you need to do is define methods in the Component class that will be common for files and folders. Then declare the File and Folder classes to each derive from the Component class and override the methods that make sense to them.

Some of the methods may only apply to files, some only to folders, and some methods may apply to both. The Folder class will be most interested in the child manipulation methods. Each of these methods will work with Component instances so that you can add a File or a Folder with the same method. This is the key to this pattern – being able to treat all the objects as if they are of the same type.

A file system example follows the hierarchy very well, but it may not appear at first to be the best example of this pattern because files and folders usually behave very differently. It can still work as an example as long as you remember that what you see as the end user of an application doesn’t always match what the code sees. The code can still treat files and folders the same even if it also displays them to you as if they’re different.