Strategy by

Define a family of algorithms, encapsulate each one, and make them interchangeable.
Strategy lets the algorithm vary independently from clients that use it.

Motivation

Strategy pattern enables us to dynamically assign an algorithm to solve a problem at hand. So to apply this pattern we must have a problem, that has multiple solutions and none of them should be clearly superior to others in every way.

For games we can use pathfinding as an excellent example. The main task of pathfinding is to create a path from the current location of the character to the location they want to reach. At first it may seem like a single algorithm might be superior, as we obviously want the shortest path as fast as possible. Although what if there are multiple paths with the same length? One option is to pick the algorithm that seems more reasonable in the game based on game design. Even better would be to use both, but on characters with different themes to add some variation.

 

So even at the very base level there can be some benefits for providing different solutions for finding a path. By also considering game design, the options for different pathfinding strategies increase exponentially. We could also create additional pathfinding algorithms for characters that can fly or swim from those that can't. Some characters might start moving faster by going in a straight line for longer or others might gain some defensive bonuses for zig-zagging.

So far the obvious answer has been in all cases to use A* with different heuristics, so by sacrificing some code quality and run speed we might be able to fit them all in a single implantation. However in strategy games a quite common unit is the harvester or worker. It is a unit who has to collect resource by moving to a resource node and then returning to the drop off location. The problem here is quite different, as we do not know the target location, we just know it should have a resource we are interested in. So to solve this problem with A* we would have to check every resource location in the world and run pathfinding to this location. A more reasonable option however would be to use Dijkstra from the drop off location and find every possible path to this type of resource in ascending order. The singe run would likely take a bit longer than a single run of A*, but we would end up with all the paths for all of the harvesters until the map changes.

 

Structure

 

Strategy Pattern Diagram

Example Uses

  • Design Patterns: Elements of Reusable Object-Oriented Software provides an example of using strategy pattern to implement different line break strategies for a text viewing application.
;