Design Pattern Revisited: Strategy Pattern
In my first post on design patterns about a month ago I discussed the Strategy Pattern, and then about a week later I realized that the my example for that post actually used the Template Method Pattern and not the Strategy Pattern— so I offered up a rain check on a decent example of the Strategy Pattern. Well, digging into one of our internal apps at 8th Light I came across a whopper of an example.
What we have is an entire set of classes that need to respond to the same methods, for example a “print” method, but the way that each of those classes implements the method is slightly different depending on what the object needs. So, in order to implement each one with the general purpose “print” commands, we pass each specific object into a single, abstract Strategy class. Here’s an example:
class FileStrategy
attr_accessor :strategy
def initialize(strategy)
@strategy = strategy
end
def print
@strategy.print
end
end
And here’s two individual objects/classes:
class JpgPrintStrategy
def print
*...some methods specific to printing a jpg...*
end
end
class PdfPrintStrategy
def print
*...some methods specific to printing a PDF...*
end
end
Now we could just create a FileStrategy.new(JpgObject)
or FileStrategy.new(PdfObject)
and know that we could call the print
method and get the output we needed. Of course this example is a little contrived because a file would need to be able to do a lot more than just print, but at least we can see how it’s possible to “vary the algorithm” with the Strategy Pattern.