Applied Design Patterns with Java

Behavioral :: Strategy (315) {C ch 24}


Collaborations

Consequences

The Strategy pattern has the following benefits and drawbacks:

  1. Families of related algorithms. Hierarchies of Strategy classes define a family of algorithms or behaviors for contexts to reuse. Inheritance can help factor out common functionality of the algorithms
  2. An alternative to subclassing. Inheritance offers another way to support a variety of algorithms or behaviors. Subclass a Context class directly to give it different behaviors. But this hard-wires the behavior into Context. It mixes the algorithm implementation with Context's, making Context harder to understand, maintain, and extend. And it doesn't allow varying the algorithm dynamically. The result is many related classes whose only difference is the algorithm or behavior they employ. Encapsulating the algorithm in separate Strategy classes allows varying the algorithm independently of its context, making it easier to switch, understand, and extend.
  3. Strategies eliminate conditional statements. The Strategy pattern offers an alternative to conditional statements for selecting desired behavior. When different behaviors are lumped into one class, it's hard to avoid using conditional statements to select the right behavior. Encapsulating the behavior in separate Strategy classes eliminates these conditional statements. Code containing many conditional statements often indicates the need to apply the Strategy pattern.
  4. A choice of implementations. Strategies can provide different implementations of the same behavior. The client can choose among Strategies with different time and space trade-offs.
  5. Clients must be aware of different Strategies. The pattern has a potential drawback in that a client must understand how Strategies differ before it can select the appropriate one. Clients might be exposed to implementation issues. Use the Strategy pattern only when the variation in behavior is relevant to clients.
  6. Communication overhead between Strategy and Context. The Strategy interface is shared by all ConcreteStrategy classes whether the algorithms they implement are trivial or complex. It's likely that some ConcreteStrategies won't use all the information passed to them through this interface; simple ConcreteStrategies may use none. So there will be times when the context creates and initializes parameters that never get used. If this is an issue, then make tighter coupling between Strategy and Context.
  7. Increased number of objects. Strategies increase the number of objects in an application. Try to reduce this overhead by implementing Strategies as stateless objects that contexts can share. Any residual state is maintained by the context, which passes it in each request to the Strategy object. Shared Strategies should not maintain state across invocations. The Flyweight (195) pattern describes this approach in more detail.

Catalog Behavioral Prev Next