We know that strategy design pattern falls under behavioural design pattern which are categorized by the fact that they represent some sort of object relationships. Can anybody explain in strategy how object relationship is maintained and between whom. We create a context which holds the different implementations and client will choose one of them at runtime and can change also in another scenario. But how object relationship is maintained here and what are those two objects.
Asked
Active
Viewed 192 times
1 Answers
0
The Strategy pattern simply represents an algorithm using an object. The relationship here is between the object that invokes the strategy and the object that represents the strategy.
interface FooSorter {
List<Foo> sort(List<Foo> input);
}
class FooMergeSorter implements FooSorter { /* ... */ }
class FooHeapSorter implements FooSorter { /* ... */ }
/** The only thing you need to know about this class is that it needs Foo sorted. */
class YourContainerClass {
FooSorter sortStrategy = new FooHeapSorter();
void doSomething(List<Foo> listOfFoos) {
// Sort according to the strategy.
List<Foo> sortedList = sortStrategy.sort(listOfFoos);
// ...
}
}
In this sense, it's the responsibility of the container class (above, YourContainerClass
) to either select a strategy or allow one to be assigned. All of the other properties of their use--instance control, or how they're provided (via your context), or how they're assigned on the class that invokes--fall outside the scope of the pattern.
See this answer for more about the Strategy pattern and how it fits in among other design patterns.

Community
- 1
- 1

Jeff Bowman
- 90,959
- 16
- 217
- 251