Skip to content

Strategy

A pattern that encapsulates algorithms with the same goal behind an interface so they can be swapped at runtime.

  • When AI attack behavior should change by situation.
  • When aiming or movement policies differ by character.
  • Strategy Interface
  • Concrete Strategy
  • Context

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

using UnityEngine;
public interface IAimStrategy
{
Vector3 GetAimPosition(Transform shooterTransform, Transform targetTransform);
}
public sealed class DirectAimStrategy : IAimStrategy
{
public Vector3 GetAimPosition(Transform shooterTransform, Transform targetTransform)
{
return targetTransform.position;
}
}
public sealed class LeadAimStrategy : IAimStrategy
{
public Vector3 GetAimPosition(Transform shooterTransform, Transform targetTransform)
{
return targetTransform.position + targetTransform.forward * 0.5f;
}
}
  • 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 context swaps algorithms through a strategy interface.

Strategy Flow