Strategy Pattern

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

When is it a StrategyPattern and when is it StatePattern? I have heard the quote "eventually everything looks like a Strategy" (can't remember the attribution), but I still can't see how a Strategy is distinct from a State.

Isn't it active (Strategy) vs. passive (State) ? For instance, you will compare the time, cost or distance estimates for different modes of travel (on foot, by metro, by car, for instance) by passing your parameters to appropriate TravelStrategy objects; whereas a TravelMode could use the StatePattern to say of a given Traveler object that she prefers, at various times, to use her car, take the metro, or go on foot.

Strategy and State are pretty similar. Both have a "context", an original object that is split into pieces, which are the strategy or the state, and both organize those pieces into a class hierarchy so that instead of having a case statement to choose between the pieces, the context sends a message to the current piece, and the code is selected using polymorphism. However, when I am using them I tend to think differently.

A strategy is an algorithm. Strategies often have internal variables that record the state of the algorithm. At the end of the algorithm, the variables might record the result, but in general they are only meaningful during the execution of the algorithm. A strategy is either selected by an outside agent or by the context. A strategy tends to have a single "start" method, and it calls all the rest. There is a lot of cohesion between the methods of a strategy.

In contrast, a state usually has no variables. ("State has no state", is what I say.) A state usually selects the next state of its context. A state tends to have lots of unrelated methods, so there is little cohesion between the methods of a state.

Perhaps this is not enough reason to distinguish between the two patterns. But I find enough uses of pure State and Strategy that I don't mind those times when the design ends up half one and half the other. --RalphJohnson
In visitor pattern the object structure accepts a visitor and performs visit on it. In strategy the only difference I could notice was that the composite or object structure composes a strategy object and calls Algorithm. Aren't these two patterns essentially the same? Or rather can I put it like strategy is a cutdown version of visitor or a visitor on a single type of element? -- Praveen

In the StrategyPattern, the context points to a strategy and delegates to it. There is no context in the VisitorPattern and the visitor is often created each time it is used. The VisitorPattern is based on DoubleDispatching?, and there is none in the StrategyPattern. As far as I can see, these patterns have little to do with each other. --RalphJohnson
Both are examples of ObjectifiedBehavior. I try to think of the Strategy as a generalization of the State. State is a specialization of the Strategy where behaviour is based on the state of the object. --SaurabhBanerjee
While the structure of the two patterns is the same or similar, I think the intent is what is different. The StatePattern is a way to vary an object's behavior dynamically, whereas the StrategyPattern is a way to vary the implementation. That's how I see it anyway. -- JasonArhart
In my opinion, the StrategyPattern and the StatePattern are not strongly related as suggested by many. The primary intention of the StrategyPattern is [behavioral] parameterization. The StrategyPattern allows the client of a software component to parameterize the component by behavior. The primary intention of the StatePattern is the simplification of complex logic related to the implementation of state machines or stateful objects. In my opinion, these are almost completely unrelated issues. In my opinion, the StrategyPattern is more closely related to the TemplateMethodPattern and very strongly related to the FunctorObject pattern. -- VesaKarvonen

Are there similarities between StrategyPattern and AbstractFactoryPattern?

The only similarity I see is that they both use a common interface to abstract a common behaviour. AbstractFactoryPattern is in CategoryCreationalPatterns, as opposed to a StrategyPattern, which belongs to CategoryBehavioralPatterns. In fact, you can use AbstractFactoryPattern to instantiate your strategies (if it's applicable for your problem, of course).
Can you say "plug-in"? --mt
This is my speculation, but I think that from an intent point of view, strategy means "same result, different way to get there." Sorting algorithms are the canonical example. I might be wrong here, but most of the things I used to call strategy is really just abstraction/polymorphism. I guess the real question here is, is strategy: a.) different ways to get the same result or b.) different ways to do the same thing? Actually, the more I think about it, the more I realize that my initial assumption is probably incorrect. It seems that strategy is just different ways to do the same (abstract) thought/thing (e.g. Compressing a file - zip, rar, etc.). So then, maybe (almost) everything IS just a strategy ;)

A strategy is an (<- SINGULAR) abstracted plan for getting from an (potentially) abstract set of initial conditions to a (potentially) abstract set of final conditions. Every piece of imperative code we ever write with a purpose exhibits some sort of strategy - not so much for constraint/logic programming and some functional programming (where the strategy isn't expressed and is instead left to the compiler). When you instantiate some of the abstract variables in a strategy, you get either a concrete plan (rarely) or another strategy (which will still have 'if' conditions and various other contingencies), which is more likely. StrategyPattern is useful when you have many strategies - many plans for getting from the same set of initial conditions to the same set of final conditions; if you abstract based on these initial and final conditions, you can swap out one strategy for another. At this point you end up with many different strategies and thus 'different ways' <- PLURAL. Of course, there isn't much point to StrategyPattern unless you (a) DO have more than one strategy available to you, and (b) can derive some sort of benefit from the ability to change strategies (e.g. controlling memory costs and processing time, completeness of results, etc.). One can usefully abstract over search strategies, sorting strategies, etc. - even planning strategies and learning strategies.

Note that planning systems make plans but don't require strategies - they can come up with a solution 'from scratch' every single time without relying upon any pre-fabricated plans. But any decent learning system (well, at least those with planning support) would eventually come up with heuristic strategies to be applied in 'common' situations (based on analysis of failure and success of its own prior attempts and the conditions surrounding them). It might not come up with formal strategies, though. And it might not come up with 'good' strategies, either - unless you give it both heuristics AND goals for optimizing the strategies themselves (e.g. less cost, less damage, less effort, less energy); without a motivator for efficiency, a system will simply build strategies over what seems to have worked and what hasn't, no matter how inefficient the successes have been.

Possible downsides: GranularityOfVariation
See also: FacadeMementoStrategy, DesignPatterns, ExplicitStrategyPattern, StatePattern, TableOrientedProgrammingDiscussion
CategoryPattern, CategoryPolymorphism

EditText of this page (last edited May 30, 2012) or FindPage with title or text search