Our review of the behavioral design patterns moves on to look at the Strategy pattern.  This is one that you might not recognize from the name.  However, it is relatively common in use (or at least it should be).

The Strategy Pattern Defined

As always, we will start with the “Gang of Four” intent to set the stage for our discussion.

“Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it”

Some people start to hear static when the word algorithm is used.  It seems too theoretical and does not apply to a practical approach.  Unfortunately, that is the core aspect of a strategy.  There is a process you are following, and you want to abstract that to make it easy to apply the exact method (algorithm) for the proper context.  The example from the book that is probably familiar to you is handling the line feed for a bunch of text.  You will use a different value for raw text, HTML, XML, RTF, etc.  Thus, a strategy for a line feed allows you to create a handful of solutions and then plug them as needed for a given type of content.

Applying The Pattern

When it comes to implementation, the strategy often starts with a root or base class.  That might even be an interface if there is no need for core functionality among the strategy classes.  Then each concrete strategy class will inherit from that base class.  This provides the interface to call or execute the strategy while allowing us a variable number of ways to implement it.

Java, PHP, C#, etc.

Although the implementation can get a little complex for this pattern, the syntax and language support is minimal.  An interface and inheritance are nice to have, but you can get away without an interface in a pinch.  Therefore, an example of this pattern that you can find will likely be easy to translate to any language you want for implementation.

Rob Broadhead

Rob is a founder of, and frequent contributor to, Develpreneur. This includes the Building Better Developers podcast. He is also a lifetime learner as a developer, designer, and manager of software solutions. Rob is the founder of RB Consulting and has managed to author a book about his family experiences and a few about becoming a better developer. In his free time, he stays busy raising five children (although they have grown into adults). When he has a chance to breathe, he is on the ice playing hockey to relax or working on his ballroom dance skills.

Leave a Reply