←All patterns
Behavioral

Strategy

Swap out an algorithm at runtime by hiding each variant behind a common interface.

What Is It?

The Strategy pattern pulls a family of interchangeable algorithms out of the class that uses them. The user — the context — holds a reference to an interface like IAttackStrategy and calls Attack(target) without knowing whether a sword, a bow or a fireball is behind it.

Each concrete strategy (MeleeAttack, RangedAttack, MagicAttack) encapsulates its own range, damage and effects. Changing how the character fights means assigning a different object to one field, not editing an ever-growing if/else chain.

The strategies here are plain C# classes, but in production they are often ScriptableObjects: a designer creates a “Fire Staff” asset, tunes its numbers in the Inspector and drags it into the weapon slot. Picking up a new weapon at runtime simply swaps the reference.

When Is It Used?

Use it when one behaviour has several variants that you want to choose or change at runtime: weapons, AI targeting rules, movement modes, difficulty curves, pathfinding heuristics.

It is a good refactor whenever a method starts with switch (weaponType) and each branch is substantial. Each branch becomes a class with a single responsibility.

If there are only two tiny variants that never change at runtime, a simple parameter or a delegate (Func<float, float>) is lighter than a full interface and set of classes.

Interactive Demo

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

Strategy Pattern
strategyMeleeAttackdummy HP200hits0
Attacker.strategy :IAttackStrategy=
MeleeAttack
Dummy
Attacker
Console
Press a button to see what happens…

Code

Assets / Scripts / Behavioral/ Strategy ›StrategyTester.cs
using UnityEngine;

namespace Patterns.Behavioral.Strategy
{
    /// <summary>
    /// Client: picks strategies at runtime and tells the attacker to
    /// attack. Swapping weapons is just reassigning a reference.
    /// </summary>
    public class StrategyTester : MonoBehaviour
    {
        [SerializeField] private Attacker attacker;
        [SerializeField] private Transform dummy; // must have an IDamageable component
        [SerializeField] private Rigidbody arrowPrefab;

        private IAttackStrategy melee;
        private IAttackStrategy ranged;
        private IAttackStrategy magic;

        private void Awake()
        {
            melee = new MeleeAttack();
            ranged = new RangedAttack(arrowPrefab);
            magic = new MagicAttack();
            attacker.SetStrategy(melee);
        }

        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.Alpha1)) attacker.SetStrategy(melee);
            if (Input.GetKeyDown(KeyCode.Alpha2)) attacker.SetStrategy(ranged);
            if (Input.GetKeyDown(KeyCode.Alpha3)) attacker.SetStrategy(magic);

            if (Input.GetKeyDown(KeyCode.Space) && dummy.TryGetComponent(out IDamageable target))
                attacker.AttackTarget(target);
        }
    }
}
4 files · namespace Patterns.Behavioral.StrategyC# · UTF-8 · LF

Before & After

Real-world smell: an attacker that switches on its weapon type. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

Attacker holds an AttackType enum. AttackTarget uses one switch to pick a range and a second switch to run the melee, ranged or magic logic inline, and it carries an arrowPrefab that only one branch uses.

Adding a weapon means editing both switches in a class every enemy shares, and it is easy to update one and forget the other. The three attacks cannot be tuned or tested separately, and designers cannot add a variant without a programmer.

✓ What changed

  • The AttackType enum, both switches and the arrowPrefab field are gone from the attacker.
  • AttackTarget asks the current IAttackStrategy for its Range and then calls strategy.Attack(transform, target).
  • Each attack now lives in its own class (MeleeAttack, RangedAttack, MagicAttack), together with its own data such as the arrow prefab.
  • SetStrategy swaps behaviour at runtime, and a new weapon is a new class with no change to Attacker.
Attacker.Before.cs → Attacker.After.cs+8/−37
11 using UnityEngine;
22
33 namespace Patterns.Behavioral.Strategy
44 {
55 /// <summary>
6− /// Without Strategy: the attacker knows every kind of attack and
7− /// picks one with a switch on an enum.
6+ /// With Strategy: the attacker holds one IAttackStrategy and delegates
7+ /// to it. Each attack's range and logic live in its own class.
88 /// </summary>
99 public class Attacker : MonoBehaviour
1010 {
11− public enum AttackType { Melee, Ranged, Magic }
11+ private IAttackStrategy strategy;
1212
13− [SerializeField] private AttackType attackType = AttackType.Melee;
14− [SerializeField] private Rigidbody arrowPrefab; // only used by Ranged
13+ public void SetStrategy(IAttackStrategy next) => strategy = next;
1514
16− public void SetAttackType(AttackType next) => attackType = next;
17−
1815 public void AttackTarget(IDamageable target)
1916 {
20− float range = attackType switch
21− {
22− AttackType.Melee => 1.5f,
23− AttackType.Ranged => 15f,
24− _ => 10f,
25− };
17+ if (strategy == null) return;
2618
2719 float distance = Vector3.Distance(transform.position, target.Transform.position);
28− if (distance > range)
20+ if (distance > strategy.Range)
2921 {
30− Debug.Log($"{attackType}: target out of range ({distance:0.0}m)");
22+ Debug.Log($"{strategy.Name}: target out of range ({distance:0.0}m)");
3123 return;
3224 }
3325
34− switch (attackType)
35− {
36− case AttackType.Melee:
37− target.TakeDamage(25);
38− break;
39−
40− case AttackType.Ranged:
41− Vector3 direction = (target.Transform.position - transform.position).normalized;
42− Rigidbody arrow = Instantiate(arrowPrefab, transform.position, Quaternion.LookRotation(direction));
43− arrow.linearVelocity = direction * 30f;
44− Destroy(arrow.gameObject, 2f);
45− target.TakeDamage(12);
46− break;
47−
48− case AttackType.Magic:
49− foreach (Collider hit in Physics.OverlapSphere(target.Transform.position, 3f))
50− {
51− if (hit.TryGetComponent(out IDamageable victim))
52− victim.TakeDamage(18);
53− }
54− break;
55− }
26+ strategy.Attack(transform, target);
5627 }
5728 }
5829 }

Advantages & Disadvantages

+ Advantages

  • Algorithms are interchangeable at runtime without touching the context.
  • New variants are added as new classes, leaving existing, tested code alone.
  • Each strategy is small and isolated, which makes it easy to tune and unit test.

− Disadvantages

  • More types to manage; trivial variations may not justify their own class.
  • Callers must know enough about the strategies to choose the right one.
  • Strategies with very different data needs can force a bloated, lowest-common-denominator interface.

Tips

  1. 01Make strategies ScriptableObject assets so designers can create and balance variants without code changes.
  2. 02Keep strategies stateless where possible, so a single asset can be shared by many attackers.
  3. 03Pass a small context (attacker transform, target, stats) into the method instead of giving strategies references to everything.
  4. 04Strategy and State look alike in code. The difference is intent: a strategy is chosen from outside, while states trigger their own transitions.
  5. 05For one-off behaviours, a C# delegate or lambda is a perfectly valid lightweight strategy.