In my previous post on the Strategy pattern I mentioned that the way I had implemented the pattern in my Minimax players I also used aspects of the Template Method pattern. Well, as I read more about the Template Method pattern this week I realized that the Minimax Player example is actually entirely the Template Method pattern, so now I’ll use the code as an example here and I’ll need to do a Strategy Pattern redux post.
In Design Patterns in Ruby Olsen describes the Template Method pattern as the simplest of the Gang of Four patterns. He titled the chapter “Varying the Algorithm with the Template Method” because the Template method allows you to implement an algorithm that may need to act differently depending on different conditions. For example, my Max and Min players both need to compare a best score and a new score to find out which is better, but the result will be different because the Min player wants a lower score and the Max player wants a higher score.
The Template method is built around inheritance to separate the things that stay the same into a super class and then pushes the things that change down into sub classes.
The Strategy Pattern, on the other hand, does not use inheritance.
When I was first getting the Minimax algorithm to work I wrote out everything very explicitly so that I could think through every step— and ended up with the 45 line mess of a method (including a couple of ugly supporting methods) that you can see in the first gist below. There is Minimax player logic tied into my scoring method, lots of repetitive code, and an ugly series of if-else statements that switched the behavior based on if the player was max or min.
However, by using the Template Method pattern I was able to create a MinimaxPlayer super class with things that stayed the same (two attributes) and then moved the varying compare methods down into sub-classes (viewable in the second gist). This allowed me to separate out the Minimax player logic as well as do a significant refactor of the scoring and other methods (the third gist). I was pretty happy with how the new Minimax scoring method came out, but I’m thinking I might actually just get right rid of the MinimaxPlayer super class and inheritance and officially use the Strategy Pattern.
Ugly first run (but I was so happy to finally have a working scoring algorithm)
Template Method pattern applied to Minimax Players and compare method