←All patterns
Structural

Composite

Treat a single object and a whole tree of objects through the same interface.

What Is It?

Composite arranges objects into a tree where leaves and branches share one interface. A leaf does the work itself; a composite holds children and forwards the call to each of them, usually combining the results on the way back up.

Picture an RTS army. A Soldier has an attack power. A Squad contains soldiers and maybe other squads. An Army contains squads. All of them implement IUnit, so army.GetPower() walks the whole tree and sums it, while soldier.GetPower() simply returns a number. The caller never checks which one it holds.

Unity itself is built on this idea: the Transform hierarchy is a composite, and moving a parent moves every child. The pattern lets your own game data get the same uniform treatment for things like squads, UI menus, quest objectives, skill trees and behaviour trees.

When Is It Used?

Use it whenever your data is naturally a tree and you want to run the same operation at any level: select a squad or a single soldier, mute a whole audio category or one source, complete a quest step or the full quest chain.

It is a strong fit for behaviour trees and dialogue graphs, where a sequence node and an action node must both answer Tick() and return a status.

Avoid it when leaves and branches really need different operations. Forcing an Add(child) method onto a soldier that can never have children just moves the type check to runtime errors.

Interactive Demo

Click the controls and watch the objects collaborate. The console mirrors what the C# code below would log.

Composite Pattern
squads2soldiers3power?
tap a squad to select it
🏰
Army
Squad · composite
K
12
A
8
P
10
Console
Press a button to see what happens…

Code

Assets / Scripts / Structural/ Composite ›ArmyTester.cs
using UnityEngine;

namespace Patterns.Structural.Composite
{
    /// <summary>
    /// Builds a small army tree and calls the same methods on the root,
    /// a squad and a single soldier.
    /// </summary>
    public class ArmyTester : MonoBehaviour
    {
        private Squad army;

        private void Start()
        {
            var alpha = new Squad("Alpha");
            alpha.Add(new Soldier("Knight", 12));
            alpha.Add(new Soldier("Archer", 8));

            var bravo = new Squad("Bravo");
            bravo.Add(new Soldier("Pikeman", 10));

            army = new Squad("Army");
            army.Add(alpha);
            army.Add(bravo);

            Debug.Log($"Army power: {army.GetPower()}");   // 30
            Debug.Log($"Alpha power: {alpha.GetPower()}"); // 20
        }

        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.Space))
                army.Attack(); // one call, every soldier swings
        }
    }
}
4 files · namespace Patterns.Structural.CompositeC# · UTF-8 · LF

Before & After

Real-world smell: army code that loops over squads and soldiers separately. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

The army is a list of SquadData, each holding a list of Soldier. Computing the total power and ordering an attack both need two nested loops that treat squads and soldiers differently.

The depth is baked into the code. A squad inside a squad, or a lone hero directly in the army, needs a third loop or a special case in every method that walks the army, and each new operation (retreat, heal, count) copies the same loops again.

✓ What changed

  • The private SquadData class and the List<SquadData> are gone; the army is now a Squad, and squads and soldiers share IUnit.
  • Squads are added with army.Add(...) exactly like soldiers, so the tree can be any depth.
  • The nested power loops become one call, army.GetPower(), and the nested attack loops become army.Attack().
  • The recursion lives in Squad, so a new operation is one method on IUnit instead of another set of loops in every caller.
ArmyTester.Before.cs → ArmyTester.After.cs+11/−28
1−using System.Collections.Generic;
21 using UnityEngine;
32
43 namespace Patterns.Structural.Composite
54 {
65 /// <summary>
7− /// Without Composite: squads and soldiers are different shapes, so the
8− /// army code loops level by level and must know the exact depth.
6+ /// With Composite: squads and soldiers share IUnit, so the army is one
7+ /// tree and every operation is a single call on its root.
98 /// </summary>
109 public class ArmyTester : MonoBehaviour
1110 {
12− private class SquadData
13− {
14− public string Name;
15− public List<Soldier> Soldiers = new();
16− }
11+ private Squad army;
1712
18− private readonly List<SquadData> army = new();
19−
2013 private void Start()
2114 {
22− var alpha = new SquadData { Name = "Alpha" };
23− alpha.Soldiers.Add(new Soldier("Knight", 12));
24− alpha.Soldiers.Add(new Soldier("Archer", 8));
15+ var alpha = new Squad("Alpha");
16+ alpha.Add(new Soldier("Knight", 12));
17+ alpha.Add(new Soldier("Archer", 8));
2518
26− var bravo = new SquadData { Name = "Bravo" };
27− bravo.Soldiers.Add(new Soldier("Pikeman", 10));
19+ var bravo = new Squad("Bravo");
20+ bravo.Add(new Soldier("Pikeman", 10));
2821
22+ army = new Squad("Army");
2923 army.Add(alpha);
3024 army.Add(bravo);
3125
32− int armyPower = 0;
33− foreach (SquadData squad in army)
34− foreach (Soldier soldier in squad.Soldiers)
35− armyPower += soldier.GetPower();
36−
37− Debug.Log($"Army power: {armyPower}"); // 30
26+ Debug.Log($"Army power: {army.GetPower()}"); // 30
3827 }
3928
4029 private void Update()
4130 {
4231 if (!Input.GetKeyDown(KeyCode.Space)) return;
4332
44− // A squad inside a squad would need a third nested loop here, and in every other method.
45− foreach (SquadData squad in army)
46− {
47− Debug.Log($"{squad.Name}: charge! ({squad.Soldiers.Count} units)");
48− foreach (Soldier soldier in squad.Soldiers)
49− soldier.Attack();
50− }
33+ army.Attack(); // recurses through squads of any depth
5134 }
5235 }
5336 }

Advantages & Disadvantages

+ Advantages

  • Clients use one interface for one object or ten thousand, so calling code stays tiny.
  • New leaf or composite types slot in without touching existing traversal code.
  • Recursive aggregation (total power, total weight, bounds) falls out naturally.

− Disadvantages

  • The shared interface can become too general, making it hard to restrict which children a composite accepts.
  • Deep trees mean deep recursion; naive per-frame traversal of large hierarchies can show up in the profiler.
  • Debugging a single result means walking the tree to find which node contributed what.

Tips

  1. 01Cache aggregate values and invalidate them when children change (a dirty flag) instead of recomputing every frame.
  2. 02Keep child-management methods (Add, Remove) on the composite type only, not on the shared interface, to stay type-safe.
  3. 03For scene objects, you can lean on GetComponentsInChildren<IUnit>(), but a plain C# tree is faster and easier to test.
  4. 04Guard against cycles if your tree is editable at runtime: never let a squad become its own descendant.
  5. 05Visitors pair well with composites when you need many unrelated operations over the same tree.