Design Patterns: The Strategy Pattern

Have you guys played Pyre yet? No? Well do. It is one of my favourite games this year. It is also a sort of Strategy game… kind of… it is hard to define what it is really, but it has strategy elements!

In this post I am going to talk about the Strategy pattern. In wikipedia term, the Strategy pattern is a behavioural software design pattern that enables an algorithm’s behaviour to be selected at runtime. Fancy.

In game development terms, we could look at enemies. In an action game, maybe you want the enemies to have different behaviours when they fight the player. I am going to use like an Ace Combat style game as an example. Each Enemy Pilot has some standard stuff, but we want the pilot AI to do many different things. We could use the strategy pattern for this.

public class EnemyPilot
{
    .. Other code here
    private IPilotAI _pilotAI;
    void Update()
    {
         _pilotAI.Update();
    }
}

In the above C# code, I have a class that is the EnemyPilot that contains the IPilotAI interface that we can set at runtime. We can now make a number of AI behaviours that use the Pilot AI interface. This is much better than inheriting from the whole EnemyPilot class each time and we are encapsulating the only thing that varies, i.e. the Pilot AI. And really it as that. Cool huh?

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Verify that you are not a robot! (If you are unlucky) *