Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • System Design Tutorial
  • What is System Design
  • System Design Life Cycle
  • High Level Design HLD
  • Low Level Design LLD
  • Design Patterns
  • UML Diagrams
  • System Design Interview Guide
  • Scalability
  • Databases
Open In App
Next Article:
Decorator Design Pattern
Next article icon

Composite Method | Software Design Pattern

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Composite Pattern is a structural design pattern that allows you to compose objects into tree structures to represent part-whole hierarchies. The main idea behind the Composite Pattern is to build a tree structure of objects, where individual objects and composite objects share a common interface. This common interface allows clients to interact with both types of objects without needing to distinguish between them.

Important Topics for the Composite Method Design Patterns

  • What are Part-Whole or Whole-Part Object hierarchies?
  • Use Cases of Composite Pattern
  • Example for Composite Design Pattern
  • Advantages of the Composite Design Patterns
  • Disadvantages of Composite Design Patterns
  • Potential Pitfalls
  • Conclusion

What are Part-Whole or Whole-Part Object hierarchies?

Example:

In a graphic design application, you might have shapes as individual elements (like circles and rectangles), and you can combine these shapes to create more complex shapes (like a smiley face with eyes and a mouth). The Composite Pattern lets you work with both simple shapes and complex shapes using the same set of operations, making it easier to manage and manipulate them.

In this context:

  • The parts are individual shapes (like circles, rectangles).
  • The wholes are the complex shapes (like a smiley face composed of circles and rectangles).

Use Cases of Composite Pattern

The Composite Pattern is useful in various scenarios, such as:

  1. Graphics and GUI Libraries: Building complex graphical structures like shapes and groups.
  2. File Systems: Representing files, directories, and their hierarchical relationships.
  3. Organization Structures: Modeling hierarchical organizational structures like departments, teams and employees.

Example for Composite Design Pattern

You are tasked with developing a software component to manage a hierarchical file system structure. The goal is to implement the Composite Pattern to seamlessly work with individual files and directories as part of a unified hierarchy.

Implementing the Composite Pattern for File System Hierarchy

Let's understand the components of the Composite Pattern using file system hierarchy example:

Key Component in the Composite Pattern

  1. Component: The Component is the common interface for all objects in the composition. It defines the methods that are common to both leaf and composite objects.
  2. Leaf: The Leaf is the individual object that does not have any children. It implements the component interface and provides the specific functionality for individual objects.
  3. Composite: The Composite is the container object that can hold Leaf objects as well as the other Composite objects. It implements the Component interface and provides methods for adding, removing and accessing children.
  4. Client: The Client is responsible for using the Component interface to work with objects in the composition. It treats both Leaf and Composite objects uniformly.

Step Wise Implementation of Composite Design Pattern

1. Component

In the file system hierarchy example, the Component is represented by the FileSystemComponenet interface. This interface defines the common interface for both leaf and composite objects. It declares a method, display(), which all classes in the hierarchy must implement.

C++
class FileSystemComponent {
public:
    virtual void display() const = 0;
};

The Component serves as the foundation for all objects within the hierarchy. Whether it's file or a directory, they all must adhere to this common interface.

2. Leaf

In the context of our file system hierarchy example, Leaf objects are the individual files. These are the objects that do not have any children. Here is an implementation of a leaf object, a file:

C++
class File : public FileSystemComponent {
public:
    File(const std::string& name, int size) : name(name), size(size) {}

    void display() const override {
        std::cout << "File: " << name << " (" << size << " bytes)" << std::endl;
    }
private:
    std::string name;
    int size;
};

Here, File is a leaf object. It implements the FileSystemComponent interface by providing a display method. It contains data specific to files, such as their name and size.

3. Composite

In the file system hierarchy example, Composite objects are directories. These are objects that contain other components, including both leaf objects (files) and other composite objects (subdirectories). Here's an implementation of a composite object, a directory:

C++
class Directory : public FileSystemComponent {
public:
    Directory(const std::string& name) : name(name) {}

    void display() const override {
        std::cout << "Directory: " << name << std::endl;
        for (const auto& component : components) {
            component->display();
        }
    }

    void addComponent(FileSystemComponent* component) {
        components.push_back(component);
    }
private:
    std::string name;
    std::vector<FileSystemComponent*> components;
};

In this example, Directory is a composite object. Like the File class, it also implements the FileSystemComponent interface by providing a display method. Additionally it, contains a vector of FileSystemComponent to store child components (files or subdirectories). The addComponent method allows adding components to the directory.

4. Client

The Client code interacts with the components through the Component interface, and it doesn't need to be aware of whether it's working with a leaf or a composite object.

C++
int main() {
    // Create leaf objects (files)
    FileSystemComponent* file1 = new File("document.txt", 1024);
    FileSystemComponent* file2 = new File("image.jpg", 2048);

    // Create a composite object (directory)
    Directory* directory = new Directory("My Documents");

    // Add leaf objects to the directory
    directory->addComponent(file1);
    directory->addComponent(file2);

    // Display the directory (including its contents)
    directory->display();

    return 0;
}

In this client code, you can see how the client interacts with both leaf (file) and composite (directory) objects uniformly, without needing to know the specific type of each object. The display method of the FileSystemComponent interface is used to display the entire hierarchy.

Diagrammatic representation of the Composite Design Pattern

Composite-Design-Pattern
UML Diagram: Composite Design Pattern

Code Implementation of the above Problem:

C++
#include <bits/stdc++.h>
class FileSystemComponent {
public:
    virtual void display() const = 0;
};
class File : public FileSystemComponent {
public:
    File(const std::string& name, int size)
        : name(name)
        , size(size)
    {
    }

    void display() const override
    {
        std::cout << "File: " << name << " (" << size
                  << " bytes)" << std::endl;
    }

private:
    std::string name;
    int size;
};
class Directory : public FileSystemComponent {
public:
    Directory(const std::string& name)
        : name(name)
    {
    }

    void display() const override
    {
        std::cout << "Directory: " << name << std::endl;
        for (const auto& component : components) {
            component->display();
        }
    }

    void addComponent(FileSystemComponent* component)
    {
        components.push_back(component);
    }

private:
    std::string name;
    std::vector<FileSystemComponent*> components;
};
int main()
{
    // Create leaf objects (files)
    FileSystemComponent* file1
        = new File("document.txt", 1024);
    FileSystemComponent* file2
        = new File("image.jpg", 2048);

    // Create a composite object (directory)
    Directory* directory = new Directory("My Documents");

    // Add leaf objects to the directory
    directory->addComponent(file1);
    directory->addComponent(file2);

    // Display the directory (including its contents)
    directory->display();

    return 0;
}

Output
Directory: My Documents
File: document.txt (1024 bytes)
File: image.jpg (2048 bytes)



Advantages of the Composite Design Pattern

  • Hierarchical Structure: The Composite Pattern provides a way to represent complex hierarchical structures of objects. You can create tree-like structures where both individual objects and composite objects (objects that contain other objects) can be treated uniformly.
  • Simplified Client Code: Clients (code that uses the composite structure) can work both with individual objects and composites without needing to know the difference. This simplifies client code, making it more intuitive and easier to maintain.
  • Flexibility: The pattern allows you to add and remove objects in the hierarchy without affecting the client code. This flexibility makes it easy to modify the structure of the tree.
  • Scalability: You can easily create more complex structures by nesting composites within composites, making it a scalable solution for modeling part-whole hierarchies.
  • Code Reusability: The pattern encourages the reuse of code. You can apply the same operations to both individual objects and composites, reducing duplication of code.

Disadvantages of Composite Design Pattern

  • Complex Implementation: Implementing the Composite Pattern can be more complex compared to a non-composite approach. It involves creating a common interface for both individual objects and compositions, which can make the code more intricate.
  • Performance Overhead: In some cases, traversing and performing operations on a composite structure can result in performance overhead, especially when dealing with deep and complex hierarchies. This is because you may need to navigate through multiple layers of objects.
  • Limited Type Safety: Since the Composite Pattern involves a common interface for both leaf and composite objects, it can lead to a lack of type safety. It's possible to call methods on composite objects that are not applicable, leading to runtime errors. This requires careful handling to ensure that only relevant operations are performed on objects.
  • Reduced Clarity: While the pattern provides flexibility for building complex structures, it can also reduce the clarity of the code. It might be less obvious when you're working with a composite structure, and this can make the code harder to understand, especially for developers who are not familiar with the pattern.
  • Extra Memory Usage: Composite structures can consume additional memory due to the need to store references to child objects within composite objects. This can be a concern when dealing with large hierarchies.

Potential Pitfalls

While the Composite Pattern is a powerful tool, it's important to be aware of some potential pitfalls:

  1. Complexity: While the Composite Pattern simplifies client code, it can make the implementation of the composite structure more complex. Managing the hierarchy and dealing with different types of objects within the hierarchy can be challenging.
  2. Performance Overhead: The pattern can introduce performance overhead, especially when dealing with deep or large hierarchies. Traversing and performing operations on composite structures may be slower than working with individual objects directly.
  3. Type Safety: In languages that do not provide strong type checking, it can be challenging to ensure type safety, as the client code may inadvertently attempt operations on incompatible objects within the hierarchy.
  4. Design Complexity: The Composite Pattern is not suitable for all scenarios. In some cases, it may be an overkill and make the design overly complex. It's essential to carefully consider whether the pattern is appropriate for the specific problem at hand.
  5. Limited Use Cases: The Composite Pattern is primarily used for part-whole hierarchies. It may not be the best choice for situations where you need more specialized behavior or interactions between objects that do not fit this structure.

Conclusion

The Composite Pattern is a fundamental design pattern for building complex hierarchical structures. It provides a uniform interface for both individual and composite objects, enabling flexible and dynamic hierarchies. By understanding its structure, advantages, use cases and potential pitfalls, you can effectively apply the Composite Pattern in your projects to create maintainable and extensible code.


Next Article
Decorator Design Pattern

T

thesunpandey
Improve
Article Tags :
  • Design Pattern
  • Geeks Premier League
  • System Design
  • Geeks Premier League 2023

Similar Reads

    Software Design Patterns Tutorial
    Software design patterns are important tools developers, providing proven solutions to common problems encountered during software development. This article will act as tutorial to help you understand the concept of design patterns. Developers can create more robust, maintainable, and scalable softw
    9 min read
    Complete Guide to Design Patterns
    Design patterns help in addressing the recurring issues in software design and provide a shared vocabulary for developers to communicate and collaborate effectively. They have been documented and refined over time by experienced developers and software architects. Important Topics for Guide to Desig
    11 min read
    Types of Software Design Patterns
    Designing object-oriented software is hard, and designing reusable object-oriented software is even harder. Christopher Alexander says, "Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way th
    9 min read

    1. Creational Design Patterns

    Creational Design Patterns
    Creational Design Patterns focus on the process of object creation or problems related to object creation. They help in making a system independent of how its objects are created, composed, and represented. Creational patterns give a lot of flexibility in what gets created, who creates it, and how i
    4 min read

    Types of Creational Patterns

    Factory method Design Pattern
    The Factory Method Design Pattern is a creational design pattern that provides an interface for creating objects in a superclass, allowing subclasses to alter the type of objects that will be created. This pattern is particularly useful when the exact types of objects to be created may vary or need
    7 min read
    Abstract Factory Pattern
    The Abstract Factory Pattern is one of the creational design patterns that provides an interface for creating families of related or dependent objects without specifying their concrete classes and implementation, in simpler terms the Abstract Factory Pattern is a way of organizing how you create gro
    8 min read
    Singleton Method Design Pattern in JavaScript
    Singleton Method or Singleton Design Pattern is a part of the Gang of Four design pattern and it is categorized under creational design patterns. It is one of the most simple design patterns in terms of modeling but on the other hand, this is one of the most controversial patterns in terms of comple
    9 min read
    Singleton Method Design Pattern
    The Singleton Method Design Pattern ensures a class has only one instance and provides a global access point to it. It’s ideal for scenarios requiring centralized control, like managing database connections or configuration settings. This article explores its principles, benefits, drawbacks, and bes
    11 min read
    Prototype Design Pattern
    The Prototype Design Pattern is a creational pattern that enables the creation of new objects by copying an existing object. Prototype allows us to hide the complexity of making new instances from the client. The existing object acts as a prototype and contains the state of the object. Table of Cont
    8 min read
    Builder Design Pattern
    The Builder Design Pattern is a creational pattern used in software design to construct a complex object step by step. It allows the construction of a product in a step-by-step manner, where the construction process can change based on the type of product being built. This pattern separates the cons
    9 min read

    2. Structural Design Patterns

    Structural Design Patterns
    Structural Design Patterns are solutions in software design that focus on how classes and objects are organized to form larger, functional structures. These patterns help developers simplify relationships between objects, making code more efficient, flexible, and easy to maintain. By using structura
    7 min read

    Types of Structural Patterns

    Adapter Design Pattern
    One structural design pattern that enables the usage of an existing class's interface as an additional interface is the adapter design pattern. To make two incompatible interfaces function together, it serves as a bridge. This pattern involves a single class, the adapter, responsible for joining fun
    8 min read
    Bridge Design Pattern
    The Bridge design pattern allows you to separate the abstraction from the implementation. It is a structural design pattern. There are 2 parts in Bridge design pattern : AbstractionImplementationThis is a design mechanism that encapsulates an implementation class inside of an interface class. The br
    4 min read
    Composite Method | Software Design Pattern
    Composite Pattern is a structural design pattern that allows you to compose objects into tree structures to represent part-whole hierarchies. The main idea behind the Composite Pattern is to build a tree structure of objects, where individual objects and composite objects share a common interface. T
    9 min read
    Decorator Design Pattern
    The Decorator Design Pattern is a structural design pattern that allows behavior to be added to individual objects dynamically, without affecting the behavior of other objects from the same class. It involves creating a set of decorator classes that are used to wrap concrete components.Important Top
    9 min read
    Facade Method Design Pattern
    Facade Method Design Pattern is a part of the Gang of Four design patterns and it is categorized under Structural design patterns. Before we go into the details, visualize a structure. The house is the facade, it is visible to the outside world, but beneath it is a working system of pipes, cables, a
    8 min read
    Flyweight Design Pattern
    The Flyweight design pattern is a structural pattern that optimizes memory usage by sharing a common state among multiple objects. It aims to reduce the number of objects created and to decrease memory footprint, which is particularly useful when dealing with a large number of similar objects.Flywei
    10 min read
    Proxy Design Pattern
    The Proxy Design Pattern a structural design pattern is a way to use a placeholder object to control access to another object. Instead of interacting directly with the main object, the client talks to the proxy, which then manages the interaction. This is useful for things like controlling access, d
    9 min read

    3. Behvioural Design Patterns

`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences