←All patterns
Structural

Decorator

Stack extra behaviour onto an object at runtime by wrapping it in layers that share its interface.

What Is It?

A Decorator wraps an object, implements the same interface, and forwards calls to it while adding something of its own before or after. Because the wrapper looks exactly like the thing it wraps, you can wrap the wrapper too, building a chain of small, focused layers.

Weapon upgrades are the textbook game case. A BaseSword deals 10 damage. Wrap it in a FireDecorator and GetDamage() asks the sword, then adds burn. Wrap that in a CritDecorator and the whole result gets multiplied. The player’s attack code calls weapon.GetDamage() and has no idea how many layers are underneath.

This beats subclassing when combinations explode. You do not need FirePoisonCritSword; you need four small decorators and the ability to compose them in any order the loot system rolls.

When Is It Used?

Use it for stackable modifiers: weapon enchantments, buff and debuff layers, status effects that alter damage or speed, or logging and caching around a service.

It fits well when modifiers are picked at runtime from data (loot tables, perks, item sockets) rather than known at compile time.

Avoid it when the order of layers must be strictly controlled or when you need to inspect and remove a specific inner layer often. A flat list of modifiers processed by a single calculator is usually simpler for stat systems.

Interactive Demo

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

Decorator Pattern
layers0damage10
🗡BaseSword10
call chain (outer → inner)
🗡 BaseSword10
Describe(): Sword
Console
Press a button to see what happens…

Code

Assets / Scripts / Structural/ Decorator ›WeaponTester.cs
using UnityEngine;

namespace Patterns.Structural.Decorator
{
    /// <summary>
    /// Builds a weapon by wrapping a base sword in decorators,
    /// then attacks through the whole chain with a single call.
    /// </summary>
    public class WeaponTester : MonoBehaviour
    {
        private IWeapon weapon;

        private void Start()
        {
            weapon = new BaseSword();
            weapon = new FireDecorator(weapon);    // +5 burn
            weapon = new PoisonDecorator(weapon);  // +3 poison
            weapon = new CritDecorator(weapon);    // x2 outer multiplier

            Debug.Log(weapon.Describe()); // Sword + Fire + Poison + Crit
        }

        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.Space))
                Debug.Log($"Hit for {weapon.GetDamage()}"); // (10 + 5 + 3) * 2 = 36

            if (Input.GetKeyDown(KeyCode.F))
                weapon = new IceDecorator(weapon); // stack another layer at runtime
        }
    }
}
4 files · namespace Patterns.Structural.DecoratorC# · UTF-8 · LF

Before & After

Real-world smell: a weapon with a boolean flag for every upgrade. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

The weapon is a set of flags (hasFire, hasPoison, hasIce, hasCrit), and GetDamage and Describe check each flag in a fixed order.

Every new upgrade adds a flag and a branch in two methods. The same gem cannot stack twice, and the order is hard-coded, so hasCrit always multiplies everything, even Ice added after it. None of this can be reused by a bow or a staff.

✓ What changed

  • The four flags, GetDamage and Describe are gone; the weapon is an IWeapon built from BaseSword and decorators.
  • Each upgrade is its own class (FireDecorator, PoisonDecorator, CritDecorator, IceDecorator) that adds to the layer it wraps.
  • The wrapping order is the stacking order. Each press of F wraps another IceDecorator, so the same upgrade can stack and lands outside the crit.
  • A new upgrade is a new decorator class, and any IWeapon can use it, not only the sword.
WeaponTester.Before.cs → WeaponTester.After.cs+10/−34
11 using UnityEngine;
22
33 namespace Patterns.Structural.Decorator
44 {
55 /// <summary>
6− /// Without Decorator: every possible upgrade is a flag on the weapon,
7− /// and one method combines them in a hard-coded order.
6+ /// With Decorator: the weapon is a base sword wrapped in layers. Each
7+ /// upgrade is its own class, and the wrapping order is the stacking order.
88 /// </summary>
99 public class WeaponTester : MonoBehaviour
1010 {
11− private int baseDamage = 10;
12− private bool hasFire;
13− private bool hasPoison;
14− private bool hasIce;
15− private bool hasCrit;
11+ private IWeapon weapon;
1612
1713 private void Start()
1814 {
19− hasFire = true;
20− hasPoison = true;
21− hasCrit = true;
15+ weapon = new BaseSword();
16+ weapon = new FireDecorator(weapon); // +5 burn
17+ weapon = new PoisonDecorator(weapon); // +3 poison
18+ weapon = new CritDecorator(weapon); // x2 outer multiplier
2219
23− Debug.Log(Describe()); // Sword + Fire + Poison + Crit
20+ Debug.Log(weapon.Describe()); // Sword + Fire + Poison + Crit
2421 }
2522
2623 private void Update()
2724 {
2825 if (Input.GetKeyDown(KeyCode.Space))
29− Debug.Log($"Hit for {GetDamage()}"); // (10 + 5 + 3) * 2 = 36
26+ Debug.Log($"Hit for {weapon.GetDamage()}"); // (10 + 5 + 3) * 2 = 36
3027
3128 if (Input.GetKeyDown(KeyCode.F))
32− hasIce = true; // a second Ice gem does nothing, and Crit still multiplies it
29+ weapon = new IceDecorator(weapon); // each press stacks another layer on top
3330 }
34−
35− // Every new upgrade adds a flag here, a branch below, and a line in Describe.
36− private int GetDamage()
37− {
38− int damage = baseDamage;
39− if (hasFire) damage += 5;
40− if (hasPoison) damage += 3;
41− if (hasIce) damage += 4;
42− if (hasCrit) damage *= 2;
43− return damage;
44− }
45−
46− private string Describe()
47− {
48− string text = "Sword";
49− if (hasFire) text += " + Fire";
50− if (hasPoison) text += " + Poison";
51− if (hasIce) text += " + Ice";
52− if (hasCrit) text += " + Crit";
53− return text;
54− }
5531 }
5632 }

Advantages & Disadvantages

+ Advantages

  • Behaviour is added without modifying the wrapped class or creating subclass explosions.
  • Layers compose freely and can be added or peeled off at runtime.
  • Each decorator does one thing, so it is easy to test in isolation.

− Disadvantages

  • Order matters: a crit multiplier applied before or after flat fire damage gives different results, which can surprise designers.
  • Removing a layer from the middle of the chain is awkward; you usually rebuild the chain.
  • Many tiny wrapper objects make stack traces and debugging noisier.

Tips

  1. 01Put shared forwarding in an abstract WeaponDecorator base so concrete decorators only override what they change.
  2. 02Decide and document an ordering convention (flat bonuses first, multipliers last) and enforce it when building chains.
  3. 03Expose a Describe() method that each layer appends to; it makes tooltips and debugging trivial.
  4. 04Decorators are plain C# objects; keep them out of MonoBehaviours so they are cheap to create when an item is equipped.
  5. 05For heavy stat systems with dozens of sources, consider a modifier list instead, and keep decorators for behavioural changes like on-hit effects.