Contents

Introduction

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.

Problem

You need to provide a geographical based search engine solution where the implementing code can choose the search provider at runtime.

UML

Apex Design Patterns Strategy.png

Implementation

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:

  • Creating an interface class (the Strategy) with methods that will be implemented by other classes
  • Creating a class for each concrete Strategy that implements the methods defined in the Strategy interface

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

Apex Design Patterns Strategy Geocoder Example.png

where:

  • Context => Geocoder
  • operation() => getLatLong()
  • Strategy => GeocodeService
  • ConcreteStrategyA => GoogleMapsImpl
  • ConcreteStrategyB => MapQuestImpl

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:

The Class

Calling googleMaps

Calling MapQuest

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.

Conclusion

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.