04 Dec 2023



Advanced

The Composite design pattern is a structural pattern that lets you compose objects into tree structures to represent part-whole hierarchies. In C#, the Composite pattern typically involves the following main components:

  1. Component:

    • Declares the interface for objects in the composition.
    • Defines default behavior for all objects.
    • Represents both leaf nodes and composite nodes.
    public interface IComponent
    {
        void Operation();
    }
    
  2. Leaf:

    • Implements the Component interface.
    • Represents leaf objects that have no children.
    • Defines the behavior for individual objects.
    public class Leaf : IComponent
    {
        public void Operation()
        {
            Console.WriteLine("Leaf Operation");
        }
    }
    
  3. Composite:

    • Implements the Component interface.
    • Represents composite objects that can have children.
    • Stores child components and implements operations in terms of those components.
    public class Composite : IComponent
    {
        private List<IComponent> children = new List<IComponent>();
    
        public void Add(IComponent component)
        {
            children.Add(component);
        }
    
        public void Remove(IComponent component)
        {
            children.Remove(component);
        }
    
        public void Operation()
        {
            Console.WriteLine("Composite Operation");
            
            // Perform operation on each child
            foreach (var child in children)
            {
                child.Operation();
            }
        }
    }
    
  4. Client:

    • Manipulates objects in the composition through the Component interface.
    class Client
    {
        static void Main()
        {
            IComponent leaf = new Leaf();
            IComponent composite = new Composite();
    
            composite.Add(leaf);
            composite.Operation();
        }
    }
    

In this example:

  • IComponent is the interface that declares the common operations for both Leaf and Composite objects.
  • Leaf is a class representing individual objects without children that implement the IComponent interface.
  • Composite is a class representing composite objects that can have children. It also implements the IComponent interface. The Composite class can contain both Leaf and other Composite objects.
  • The Client manipulates objects through the common IComponent interface, treating both leaf and composite objects uniformly.

The Composite pattern allows clients to treat individual objects and compositions of objects uniformly, simplifying the client code. It is especially useful when the client needs to manipulate a hierarchy of objects in a consistent way.

software-design-patterns
composit-design-pattern
c#