Strategies

Problem

An attacking soldier in a battlefield simulation moves forward into the face of enemy fire.

A retreating soldier moves away from enemy fire.

A flanking soldier moves orthogonally across enemy fire.

This leads to the following hierarchy:

But what happens when an attacking soldier receives an order to retreat? Must we destroy the AttackingSoldier representation and create a new RetreatingSoldier representation? What happens to existing references to the former?

Solution

It's easy to modify the fields of an object, but the methods an object can execute are fixed at compile-time.

While we can't change the methods, we can change the algorithms they use. This is called the Strategy Pattern. Here's the design:

Note that two instances of the Soldier class can have different strategies.

Note that the strategy of a given instance can change dynamically.

Implementation

There are two types of strategies:

Dedicated Strategies

Shared Strategies

References

The Strategy Pattern

Ultimate Warrior