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:
-
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(); } -
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"); } } -
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(); } } } -
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:
IComponentis the interface that declares the common operations for both Leaf and Composite objects.Leafis a class representing individual objects without children that implement theIComponentinterface.Compositeis a class representing composite objects that can have children. It also implements theIComponentinterface. TheCompositeclass can contain both Leaf and other Composite objects.- The
Clientmanipulates objects through the commonIComponentinterface, 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.