Skip to content

ChainOfResponsibility

A pattern that passes a request through a chain of handlers, where each handler performs its responsibility in sequence.

  • When shields, buffs, and resistances must be applied sequentially in damage calculation.
  • When input filters need to process in stages.
  • Handler
  • Concrete Handler
  • Next Handler

The code below is a simplified Unity example based on the scenario described above.

public abstract class DamageModifierHandler
{
private DamageModifierHandler nextHandler;
public DamageModifierHandler SetNext(DamageModifierHandler nextHandler)
{
this.nextHandler = nextHandler;
return nextHandler;
}
public int Handle(int incomingDamage)
{
int updatedDamage = ModifyDamage(incomingDamage);
return nextHandler == null ? updatedDamage : nextHandler.Handle(updatedDamage);
}
protected abstract int ModifyDamage(int incomingDamage);
}
public sealed class ShieldDamageHandler : DamageModifierHandler
{
protected override int ModifyDamage(int incomingDamage)
{
return System.Math.Max(0, incomingDamage - 20);
}
}
  • Behavior is separated into smaller units, which reduces the impact of changes.
  • Adding or swapping rules is relatively safe.
  • As the number of objects and indirect calls increases, the flow can become harder to follow.
  • Ordering bugs should be pinned down with tests.

This shows the flow where a request moves through a chain and each handler takes responsibility if possible.

Chain Of Responsibility Flow