The Wayback Machine - https://web.archive.org/web/20241125005155/https://www.geeksforgeeks.org/composite-method-software-design-pattern/
Open In App

Composite Method | Software Design Pattern

Last Updated : 06 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

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.


Previous Article
Next Article

Similar Reads

Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to make a tree-like structure. The composite design pat
6 min read
Composite Design Pattern in C++
Prerequisite : Composite Design Pattern Composite pattern is one of the most widely used patterns in the industry and addresses a very significant and subtle problem. It is used whenever the user wants to treat the individual object in the same way as the collection of those individual objects for e.g you might want to consider a page from the copy
3 min read
Composite Design Pattern in Java
The Composite Design Pattern is a structural design pattern that lets you compose objects into tree-like structures to represent part-whole hierarchies. It allows clients to treat individual objects and compositions of objects uniformly. In other words, whether dealing with a single object or a group of objects (composite), clients can use them int
8 min read
Behavioral Design Pattern | JavaScript Design Pattern
Behavioral design patterns are a subset of design patterns in software engineering that deal with the interaction and responsibilities of objects. These patterns focus on how objects communicate and work together to achieve common tasks. Important Topics for the Behavioral Design Pattern in JavaScript Design Patterns Uses Cases of the Behavioral De
8 min read
Difference between Prototype Design Pattern and Flyweight Design Pattern
The major point in Prototype vs. Flyweight Design Pattern is that Prototype Design Pattern is a creational design pattern whereas Flyweight Design Pattern is a structural design pattern. In this post, we will look into this and more differences between the Prototype and Flyweight Design Patterns. Let us begin with a basic understanding of each of t
2 min read
Facade Design Pattern | JavaScript Design Pattern
Facade design pattern is a Structural design pattern that allows users to create a simple interface that hides the complex implementation details of the system making it easier to use. This pattern intends to create a simplified and unified interface for a set of interfaces hiding the implementation details making it less complex to use. Important
4 min read
Flyweight Design Pattern - JavaScript Design Pattern
The Flyweight Design Pattern is a structural design pattern used in JavaScript to minimize memory usage by sharing the data as much as possible with the related objects. Important Topics for Flyweight Design PatternDiagramatic Representation:Advantages of Flyweight design pattern:Disadvantages of Flyweight design pattern:The shared data typically c
4 min read
Mediator Design Pattern in JavaScript | Design Pattern
The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. It's particularly useful when you have a complex system with multiple objects that need to interact and you want to avoid the tight coupling that can arise from direct object-to-object communication. Important
5 min read
Difference Between Builder Design Pattern and Factory Design Pattern
Design patterns provide proven solutions to common problems in software design. The Builder and Factory patterns are two popular creational design patterns. The Builder pattern constructs complex objects step by step. In contrast, the Factory pattern creates objects without specifying their exact class. Both patterns streamline object creation but
7 min read
Mediator Design Pattern vs. Observer Design Pattern
The Mediator Design Pattern and Observer Design Pattern are both key design patterns that help manage object communication but differ in approach. The Mediator Pattern centralizes interactions, where objects communicate through a mediator, reducing dependencies. In contrast, the Observer Pattern allows objects to subscribe to changes in a subject,
5 min read
Composite Method - Python Design Patterns
Composite Method is a Structural Design Pattern which describes a group of objects that is treated the same way as a single instance of the same type of the objects. The purpose of the Composite Method is to Compose objects into Tree type structures to represent the whole-partial hierarchies. One of the main advantages of using the Composite Method
5 min read
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
State Method Design Pattern | C++ Design Patterns
In software design, managing the behavior of an object according to its internal state is a common issue. The state pattern addresses this issue by allowing an object to alter its behavior every time its internal state changes. This pattern encapsulates each state in a separate class, which makes it easier to add new states and modify existing stat
7 min read
Template Method Design Pattern | C++ Design Patterns
Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs. Important Topics for Template
7 min read
Why is Singleton Design Pattern is Considered an Anti-pattern?
Let us explore why the Singleton pattern, a popular way to ensure only one instance of a class exists, is now seen as problematic in software development. In this article, we will discuss drawbacks such as tight coupling between components, difficulty in unit testing, and issues with scalability in larger applications. Important Topics for Singleto
8 min read
CQRS Pattern vs. Repository Pattern in System Design
The CQRS Pattern and the Repository Pattern are architectural patterns used to handle data in software applications. CQRS focuses on separating commands (writes) and queries (reads) into different models. The Repository Pattern abstracts data access logic by creating a layer that mediates between the domain and the data source. Table of Content Wha
5 min read
Memento Design Pattern | C++ Design Patterns
Memento Design Pattern is a behavioral design pattern that provides a mechanism for capturing an object's internal state and restoring it to that state at a later time. This pattern is useful when we need to implement features like undo/redo functionality or when we want to save and restore an object's state for various reasons. Important Topics fo
7 min read
Design Patterns Cheat Sheet - When to Use Which Design Pattern?
In system design, selecting the right design pattern is related to choosing the right tool for the job. It's essential for crafting scalable, maintainable, and efficient systems. Yet, among a lot of options, the decision can be difficult. This Design Patterns Cheat Sheet serves as a guide, helping you on the path toward optimal design pattern selec
7 min read
Bridge Method | JavaScript Design Pattern
In software design, as systems grow and evolve, the complexity of their components can increase exponentially. This complexity often arises from the intertwining of different functionalities and features, making the system rigid, less maintainable, and harder to scale. The Bridge design pattern emerges as a solution to this problem, offering a way
9 min read
Memento Method - JavaScript Design Pattern
A behavioral design pattern in JavaScript called Memento focuses on externalizing and capturing an object's internal state so that it can later be restored. When you need to add features like undo/redo functionality, history tracking, or reverting an item to a former state, this pattern is quite helpful. Important Topics for the Memento MethodUnder
6 min read
Observer Method – JavaScript Design Pattern
Observer design pattern, a staple of behavioral design patterns in JavaScript, provides a means to establish a one-to-many relationship between objects. This design pattern is especially valuable for decoupling components and facilitating extensibility in software applications. By employing this pattern, you can have one object (the subject) notify
10 min read
Prototype Method - JavaScript Design Pattern
A Prototype Method is a JavaScript design pattern where objects share a common prototype object, which contains shared methods. The prototype method allows you to reuse the properties and methods of the prototype object, and also add new ones as needed. The prototype method is useful for performance optimization, as it avoids creating new functions
3 min read
Builder Method | JavaScript Design Pattern
The Builder design pattern is a creational design pattern used to construct complex objects by separating the construction process from the actual representation. It's especially useful when an object requires multiple steps or configurations to be created. Important Topics for the Builder Design Pattern in JavaScript Design Pattern Example without
9 min read
Strategy Method | JavaScript Design Pattern
Strategy Method or Strategy Pattern in JavaScript helps solve the problem of needing to use different methods or behaviors in your code and easily switch between them. Strategy Method is a behavioral design pattern in JavaScript that defines a family of algorithms, encapsulates each one, and makes them interchangeable. It allows the client to choos
8 min read
Iterator Method | JavaScript Design Pattern
Iterator design pattern is a behavioral design pattern that provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. It separates the responsibility of accessing and traversing the elements from the aggregate object. This pattern is widely used in many programming languages, including
4 min read
Builder, Fluent Builder, and Faceted Builder Method Design Pattern in Java
Builder Pattern is defined as a creational design pattern that is used to construct a complex object step by step. It separates the construction of an object from its representation, allowing us to create different variations of an object with the same construction code. This pattern is particularly useful when dealing with a complex object with ma
8 min read
Template Method Design Pattern in Java
Template Design Pattern or Template Method is the behavioral design pattern that defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure. This pattern falls under the category of the "behavioral" design patterns as it is concerned with how classes collaborate
10 min read
Proxy Method Design Pattern in Java
A Proxy Method or Proxy Design Pattern is a structural design pattern that provides a surrogate or placeholder for another object to control access to it. This pattern involves creating a new class, known as the proxy, which acts as an intermediary between a client and the real object. The proxy object controls access to the real object, allowing y
9 min read
Strategy Method Design Pattern in Java
Strategy method or Strategy Design Pattern is a behavioral design pattern in Java that defines a family of algorithms, encapsulates each algorithm, and makes them interchangeable. It lets the client algorithm vary independently from the objects that use it. This pattern is useful when you have a family of algorithms and want to make them interchang
11 min read
Command Method Design Pattern in Java
The Command Design Pattern in Java is a behavioral design pattern that turns a request into a stand-alone object, allowing parameterization of clients with different requests, queuing of requests, and support for undoable operations(action or a series of actions that can be reversed or undone in a system). Important Topics for Command Method Design
10 min read
three90RightbarBannerImg