Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Composite Pattern

Introduction

The Composite Pattern is a structural design pattern that allows you to compose objects into tree structures to represent part-whole hierarchies. This pattern treats individual objects and compositions of objects uniformly.

Key Concepts

  • Composite: Composed of objects and can contain both leaf and composite nodes.
  • Leaf: Represents the end nodes in the tree structure, which do not have children.
  • Component: An interface or abstract class that defines the common interface for both leaf and composite objects.

Structure

Note: The structure of the Composite Pattern typically involves three main components: the Component, Leaf, and Composite.
 
interface Component {
    void operation();
}

class Leaf implements Component {
    public void operation() {
        System.out.println("Leaf operation");
    }
}

class Composite implements Component {
    private List children = new ArrayList<>();

    public void add(Component component) {
        children.add(component);
    }

    public void operation() {
        for (Component child : children) {
            child.operation();
        }
    }
}
            

Implementation

To implement the Composite Pattern, follow these steps:

  1. Define the Component interface with common operations.
  2. Create Leaf classes that implement the Component interface.
  3. Create a Composite class that holds children components and implements the Component interface.
  4. Implement the operations in Leaf and Composite classes, delegating operations to child components in the Composite class.

public class Client {
    public static void main(String[] args) {
        Composite composite = new Composite();
        Leaf leaf1 = new Leaf();
        Leaf leaf2 = new Leaf();

        composite.add(leaf1);
        composite.add(leaf2);

        composite.operation(); // Executes operation in all children
    }
}
            

Best Practices

  • Use the Composite Pattern when you need to represent part-whole hierarchies.
  • Avoid using the Composite Pattern for simple structures as it adds unnecessary complexity.
  • Keep the interface clean and ensure that clients can work with both simple and composite objects seamlessly.

FAQ

What are the advantages of using the Composite Pattern?

The Composite Pattern simplifies client code by allowing you to treat individual objects and compositions uniformly, which leads to more intuitive and flexible structures.

When should I avoid using the Composite Pattern?

If the structure you are working with is simple or does not have a clear part-whole hierarchy, using this pattern may introduce unnecessary complexity.