This article describes how to implement a Strategy design pattern in Apex. The Strategy pattern (aka the policy pattern) attempts to solve the issue where you need to provide multiple solutions for the same problem so that one can be selected at runtime.
For the parent page to this article, and for a full list of other design patterns, go to Apex Design Patterns.
You need to provide a geographical based search engine solution where the implementing code can choose the search provider at runtime.
In order to implement a Strategy pattern in Apex, you need to define a family of algorithms, encapsulate each one, make them interchangeable, and selectable at runtime. It is implemented by:
The following code demonstrates an implementation of the Strategy pattern for the underlying GeocodeService strategy and implementations.
So the specific UML for this implementation is
Now we have our core strategy interface and implementations we need to make use of them. There are a couple of ways you may be tempted to do this however in order to decouple as much as possible consider the following:
As you can see above the calling code has a choice of implementations and the only change is the string passed to the Strategy interface.
The Strategy design pattern uses aggregation instead of inheritance which allows better decoupling between the behavior and the class that uses the behavior. This allows the behavior to be changed without breaking the classes that use it, and the classes can switch between behaviors by changing the specific implementation used without requiring any significant code changes.
See the Apex Design Patterns article for more design patterns.