Wizards´ Design Patterns — The Composite Pattern in C#
This article is about the Composite Pattern and explained with examples from the wonderful world of wizards and witches.

Table of Contents
- Basic Information about Composite Pattern
- When to use Composite Pattern
- Structure
- UML-Example
- Implementation-Example
- C# Example
- Other Articles
Basic Information about Composite Pattern
First off all: the goal with this pattern is for a class to treat all subclasses and itself exactly the same.
If one wants to create part-whole hierarchies and generate objects in a tree structure, the Composite Pattern is just the right thing. This basically involves inheritance, with the addition that a class that inherits from the superclass also stands higher in the hierarchy by calling the parent class. Thus, there are 3 different areas:
- The Component Class (Parent; abstract class or Interface)
- The Composite Class (inherits from Parent)
- The Leaf Class (inherits from Parent)
A typical example of this is the representation of hierarchical structures such as file systems, directories, menus and submenus, organizational structures, or the hierarchical representation of categories. The Composite Pattern allows organizing objects in a tree structure and accessing them uniformly. It defines a common interface for all elements in the tree, regardless of whether it is a single leaf or a composite node. This makes it easier to process tree structures and reduces the code required for different actions performed on the tree structures.
Structure
In a Composite pattern, composites can also be used as leaf components. This allows for the creation of a hierarchy of arbitrary depth and complexity, where a leaf node can consist of either a simple leaf component or a composite component.

Usually, a leaf component is considered a simple component that has no children and cannot add or remove any further components. A composite component, on the other hand, can contain both leaf components and other composite components. This creates a tree structure that can contain both simple and complex components.
So Yes: A Composite node can exclusively have other Composite components as children. It is quite common for Composite components to consist only of other Composite components and not directly contain Leaf components.
And Yes: A composite node can have any number of other composites or leafs.
UML Example

Implementation-Example

