Skip to content

Strategy Pattern

Aprius edited this page Nov 8, 2024 · 3 revisions

What

Wikipedia's defintion of the strategy pattern:

In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives runtime instructions as to which in a family of algorithms to use

Usage

Suppose you are making a game where characters can take different types of damage such as physical damage, magical damage, and elemental damage (fire, ice, etc.). We will use the Strategy Pattern to separate these damage types into separate strategies.

Create a new strategy type by inheriting from one of the following available interfaces, or you can create a new interface that suits your purpose:

  • IStrategy
  • IStrategy<out TR>
  • IStrategy<out TR, in T>
  • IStrategy<out TR, in T0, in T1>
  • IStrategy<out TR, in T0, in T1, in T2>
public class PhysicalDamage : IStrategy<float, float>
{
    public float OnExecute(float value)
    {
        return value;
    }
}

public class MagicalDamage : IStrategy<float, float>
{
    public float OnExecute(float value)
    {
        return value * 2f;
    }
}

public class FireDamage : IStrategy<float, float>
{
    public float OnExecute(float value)
    {
        return value * 0.5f;
    }
}

Create a Player class to use the damage strategy This class will act as the Context and call methods from the Strategy object.

public class Player : MonoBehaviour
{
    private IStrategy<float, float> _damageStrategy;

    public void SetDamageStrategy(IStrategy<float, float> damageStrategy) { _damageStrategy = damageStrategy; }

    public void TakeDamage(float amount)
    {
        if (_damageStrategy != null)
        {
            float finalDamage = _damageStrategy.OnExecute(amount);
            // take final damage
        }
    }
}

Now, you can use different strategies to deal damage to the target.

public class TestDamage : MonoBehaviour
{
    public Player player;

    private void Start()
    {
        player.SetDamageStrategy(new PhysicalDamage());
        player.TakeDamage(50);

        player.SetDamageStrategy(new MagicalDamage());
        player.TakeDamage(30);

        player.SetDamageStrategy(new FireDamage());
        player.TakeDamage(40);
    }
}
Clone this wiki locally