composite pattern
composite, Design Patterns, Java, OOP, structural design patterns

Design Patterns: Composite

The Composite is another design pattern that belongs to the Structural Patterns family. We use this pattern when we want to group components inside a larger component. In other words, we can build 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.

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 the composition.

Composite

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

Client

  • Manipulates objects in composition through the Component interface.

Structure

A 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 a real hierarchy. We are going to represent the pride of lions. It is a perfect example that we can see how the hierarchy works.

So, we have an interface “Panthera” and three classes that are going to implement the Panthera interface. These classes are going to implement only some operations of the 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 objects in composition and it doesn’t have children objects.

Let’s start with the 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.