2 July 2007

The Strategy Pattern

by mo

“The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.” - Head First Design Patterns

This means that at runtime you can switch the algorithm being used by a particular object. In the example attached, there are a set of characters. Each characters has a weapon that they yield! At runtime, you can switch the type of weapon that a particular character is using.

For instance if the character king was constructed to use a default weapon, at runtime you could switch out the weapon that the king uses when he is fighting. This adheres to the open/closed principle, where the king object is open for extension but closed for modification.

In the future if we wanted to add new weapons, we can add them without having to change the implementation of the king object. This allows us to switch the type of weapon the king object is using at runtime!

  King king = new King();

  king.Weapon = new Axe();

  king.Weapon = new BowAndArrow();

For more information check out…

Head First Design Patterns (Head First) by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra

Read more about this title…

DesignPatterns.Strategy.zip (5.29 KB)

books csharp designpatterns