The Composite Design Pattern is a structural design pattern that lets you compose objects into tree structures to represent part-whole hierarchies. It allows clients to treat individual objects and compositions of objects uniformly. The pattern is often used to build complex structures from simpler, reusable parts.
Here’s a C# example of the Composite Design Pattern with a use case for representing a hierarchical organization structure:
Create the Component Interface
Define an interface that represents the component in the composite pattern. It should include methods common to both leaf and composite objects.
public interface IEmployee
{
string Name { get; set; }
void Display();
}
Create the Leaf Class
Implement the component interface with a class representing a leaf node in the hierarchy. Leaf nodes have no children.
public class Employee : IEmployee
{
public string Name { get; set; }
public Employee(string name)
{
Name = name;
}
public void Display()
{
Console.WriteLine(Name);
}
}
Create the Composite Class
Implement the component interface with a class representing a composite node in the hierarchy. Composite nodes can have child components.
public class Manager : IEmployee
{
public string Name { get; set; }
private List<IEmployee> subordinates = new List<IEmployee>();
public Manager(string name)
{
Name = name;
}
public void AddSubordinate(IEmployee employee)
{
subordinates.Add(employee);
}
public void Display()
{
Console.WriteLine(Name);
foreach (var subordinate in subordinates)
{
subordinate.Display();
}
}
}
Use Case – Organization Structure
Create an organization structure using the composite pattern to represent the hierarchy of employees and managers.
class Program
{
static void Main(string[] args)
{
var ceo = new Manager("John (CEO)");
var cto = new Manager("Bob (CTO)");
var cfo = new Manager("Alice (CFO)");
var developer1 = new Employee("Charlie (Developer)");
var developer2 = new Employee("David (Developer)");
var accountant1 = new Employee("Eve (Accountant)");
cto.AddSubordinate(developer1);
cto.AddSubordinate(developer2);
cfo.AddSubordinate(accountant1);
ceo.AddSubordinate(cto);
ceo.AddSubordinate(cfo);
ceo.Display();
}
}
In this example, the Composite Design Pattern allows you to create a hierarchical organization structure with employees and managers. Both leaf (Employee) and composite (Manager) objects implement the IEmployee interface, enabling clients to work with individual employees and entire teams (managers) in a uniform way. This pattern is useful when you need to build complex structures that can be treated as a single entity, such as trees, menus, or organizational hierarchies.