views:

174

answers:

3

When implementing the Strategy Pattern, where does one put the code that determines which strategy to use? Some sample pseudo-code would help.

A: 

It all depends when you resolve which strategy to take. Sometimes one can resolve the strategy at create time, other times its a runtime thing. The simple answer it depends.

mP
+1  A: 

That decision is taken by the client of the Objects that use the Strategy Pattern. Lets say for instance that you have a Character Object that attacks other characters using a different attack style based on which Weapon the Character posesses at the time. The decision of which Strategy to use would then be made by the player of the game when she chooses which weapon the character will use.

So neither the Character nor the Weapon (the two main components of the Strategy Pattern in the example) decides which Strategy to use, rather the code that makes use of Characters and Weapons do so. By simply creating a new Weapon object (say a RayGunWeapon) and "giving" it to your Character changes the Character's behaviour.

Even though you could write code that explicitly chooses a Strategy, I think the real value of this pattern is that it can be done at run time.

Vincent Ramdhanie
A: 

How you choose to implent it will determine where the code is, and whether it is compiled in or done at runtime.

For example, if you use Dependency Injection (DI) then you can often inject a different strategy at runtime by changing an xml file.

If you use AOP then it would be at runtime or compile time, depending on how you wrote the aspect.

If you use Spring Framework then that is similar to using DI, and can be as easy as wiring in a different class.

If you use a service locator then it may be as simple as swapping in a different DLL.

Basically there are many ways to implement a strategy pattern, I just listed a few, so the comment that it depends is very correct.

James Black