Question

When I first discovered the Strategy pattern, I was amazed of the seemingly endless possibilities it offered to me and my programs. I could better encapsulate my models' behaviour and even exchange this behaviour on the fly. But the strategy could also be used to to provide traits and payload to the containing object - data that was declared in a superclass. Life was fine.

class MyMonsterAI   { float const see_radius_; virtual void attack () = 0; /* .. */ };
class ElveAI        { ElveAI() : see_radius_(150.0f) {} /* ... */ };
class CycloneAI     { CycloneAI() : see_radius_(50.0f) {} /* ... */ };
class Monster       { MyMonsterAI* ai_; };

And along came the Policy pattern and it would allow me even greater flexibility in supplying parameters to a containing class - whole classes, outfitted however I liked, albeit dynamically exchanging the behaviour... that was not too easy (unless part of the policy was to have a strategy!).

class MyMonsterTrait { typedef typename ElveAI AI; };

template< class MonsterTrait >
class Monster : public MonsterTrait::AI
{
    void idle (void) { attack(); }
};

Both patterns seem to be very powerful to me and I like to use both, in different circumstances. But I'm not sure if there are particular/typical/more-practical applications for either at some situations.

I am wondering: where do you use strategies and where policies? Where are either better suited?

Was it helpful?

Solution

Policies are largely set at compile time, while strategies are set at runtime. Further, policies are generally a C++ concept, and apply only to a minority of other languages(for example D), while strategy pattern is available to many (most?) object oriented languages, and languages that treat functions as first class citizens like python.

That being said:

  • A policy, being determined at compile time, is generally only useful for special situations where you want different application logic on a per-binary basis. For instance you might develop software that is slightly customized for each customer, whether via a web interface, or by hand, this would be a policy-based pattern.

  • A strategy is determined at runtime, and in fact can be changed on the fly. For instance you might have software which implements a different user interface and logic for the salesforce than for the support group, but they all have to deal with the same customer and licensing info so rather than having two separately maintained apps you simply have one app whose interface changes as needed.

-Adam

OTHER TIPS

I thought they were the same thing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top