Design Pattern: Strategy Pattern
Ben and I have started a Daily Design Pattern Club (current membership: 2). Ben has a couple months head-start on me in learning the patterns and is reading Head First Design Patterns with examples in Java. I’m reading Design Patterns in Ruby with examples in… Ruby.
The first pattern we covered was the Strategy Pattern— and the most basic way to think of it is as a way to implement various versions of an algorithm or method.
What if for object A you want an algorithm or method to behave one way and for object B you want that algorithm or method to behave another way? You could accomplish that with a nasty if/else statement (which I’m certainly guilty of), but what you really need is a “strategy” for A and a “strategy” for B… which brings us to the cleverly named Strategy Pattern.
One of the places I’ve used the pattern in my tic-tac-toe app was in the comparison of scores in the minimax algorithm. For my max player I only care about a newly found score if it’s higher than the current best score. For my Min player I only care about a newly found score if it’s lower than the current best score. In order to accomplish this in my first run-through of the minimax algorithm I just used the aforementioned nasty if/else statement, but it was one of the first refactors I tackled. I decided to make my max and min players two separate classes that each had their own “strategy” for the compare method. The methods are almost identical except that one uses a “>” sign and the other uses a “<” sign, but now my code is much cleaner and the intention is much clearer.
Those classes also started to use part of the Template Strategy, but that’s another post.