> Design Patterns > Composite Design Pattern

Composite Design Pattern

Composite design pattern is used to handle primitive and composite objects uniformly.


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

The intent is to compose the object to present part-whole hierarchy and handle both primitive and composite object uniformly.


  • The primitive and composite objects have to be handled differently. To distinguish these objects for manipulation increases the complexity.


  • Come up with a way to manipulate the primitive and composite object uniformly.

That means both the primitive and composite object have to be handled in similar manner.

Where it is applicable?

  • When part-whole hierarchy of object has to be represented.
  • Wherever primitive and composite objects have to be handled in similar manner.
  • Directories and Files in File system are the best example.


This is the UML structure of Composite design pattern-

Composite Design Pattern

Participant classes

  • Component class provides the interface Operation().
  • Concrete classes Leaf and Composite implements the method Operation().

How they work together?

  • Composite has instance of the class Component. It has objects which can be Leaf and Composite as well. It traverses them and does the operation on all the elements it has composed, either primitive or composite.
  • The method Add(), Remove() and GetChild() can be provided in Component or Composite, its transparency vs safety. Providing it in Component class makes it transparent and providing it in Composite class makes it safe.
  • So you can see both the primitive and composite objects are handled in similar manner.


Implementation Code

C++ Composite Pattern in C++ Composite Pattern C++ Example
C# Composite Pattern in C# Composite Pattern C# Example
Java Composite Pattern in Java Composite Pattern Java Example
Python Composite Pattern in Python Composite Pattern Python Example
JavaScript Composite Pattern in JavaScript Composite Pattern JavaScript Example
PHP Composite Pattern in PHP Composite Pattern PHP Example
Ruby Composite Pattern in Ruby Composite Pattern Ruby Example
Swift Composite Pattern in Swift Composite Pattern Swift Example
Objective-C Composite Pattern in Objective-C Composite Pattern Objective-C Example

Suresh Kumar Srivastava is founder of online learning site coursegalaxy.com and author of popular books "C In Depth", "Data Structures Through C In Depth". He has 18+ years experience in industry and worked on architecture and design of multiple products. This article is from his courses on Design Patterns.