Design Patterns: Composite

The Composite is another design pattern that belongs to Structural Patterns family. We use this pattern when we want to group components inside a larger component. In other words, we can built a hierarchy of objects.

A definition by GoF:

Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.Gang of Four

A basic structure of Composite pattern:
Component

  • Declares an interface for objects in the composition.
  • Implements the default behavior for the interface common to all classes.

Leaf

  • It implements the behavior for objects in composition.

Composite

  • It stores child components and defines the behavior for components having children.

Client

  • Manipulates objects in composition through Component interface.

Structure

Composite pattern is made easily. We just create an interface or abstract class which is going to contain all methods for “Composite” and “Leaf” classes. Then, we just need to implement our classes which are going to contain some operations of Component.

When we use Component Pattern

We use it when we want to represent hierarchies of objects.

Example

Let’s get an example with real hierarchy. We are going to represent a pride of lions. It is a perfect example that we can see how hierarchy works.

So, we have an interface “Panthera” and three classes which are going to implement Panthera interface. These classes are going to implement only some operations of Panthera interface each time.
MaleLion and FemaleLion classes are “composite” and have children in their hierarchy.

CubLion class is a “Leaf” class because it implements only the behavior for object in composition and it doesn’t have children objects.

Let’s start with Panthera interface.

MaleLion FemaleLion and CubLion classes are following.

Now we are ready to build our first pride of lions.

Output:

You can download the source code from GitHub.