Composite pattern

The composite pattern provides interface that allows to work with individual objects and with group of objects in the same way. Objects can be grouped into an any collection, for example into the tree data-structure.

For example, look to the file system. Files can be individuals objects. Folders are branches that can contain other folders and files. Then clients can work with folders and files through a single interface which includes common operations like copy, delete and etc. In the future you can easily add other kind of objects and folders, like zip archive or FTP connection.

Other example is a GUI system. Components like button can be individual objects. Containers are branches that can contain other containers and components. And clients can work with containers and components through a single interface. In the future you can easily add other kind of components and containers.

The jQuery library is a living example of this pattern. Allows you to select a collection of html elements and treat it as a single element.

advantages

  1. Makes easier to add new kinds of components.
  2. Provides flexibility of structure with manageable class or interface.