A-story-about-strategy-pattern

In a long time period, Strategy pattern is too abstract to understand for me. i can’t get the concept of strategy, and i can’t handler the situation for it. but i am totally free now, becouse i read a story about it :

Suppose Mike sometimes speeds when driving, but he doesn’t always do that. He may be stopped by a police officer. It’s possible that the police is very nice, who would let him go without any ticket or with a simple warning. (Let call this kind of police “NicePolice”.) Also it’s possible that he may be caught by a hard police and gets a ticket. (Let’s call this kind of police “HardPolice”.) He doesn’t know what kind of police would stop him, until he actually gets caught, that is, run-time.

the story can be transformed into a Class Diagram like this:

this is a perfect story for me! i completly understand the strategy is the key point, it is the abstraction of different algorithm.

now i can get a list of this situation:

  • spring mvc’s view template
  • Arrays.sort()

spring mvc’s view template

in spring mvc, there are 3 view templates(JSP,velocity,freemark) to choose. you can choose any of them , all you need to do is configuire it in the applicationContext.xml. actually, the idea of view template is the abstract of strategy, and the specific view is the real algorithm.

Arrays.sort()

when we talk about sort, we can’t avoid the compare. there are 2 ways to do this:

  • comparetor
  • Comparable
    back into Arrays.sort(), Comparable is been used.and in this situation, Comparable is the absolute strategy, the real comparable implement is the algorithm, you can change the implement to change the strategy.

anyway, i love the story. it help me to understand, hope that help you too.