CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 5 of 6 · 2 min read

Costs

What the pattern adds.

Costs and when to use it

GoF lists benefits and drawbacks. The benefits: families of related algorithms can share code through inheritance; it is an alternative to subclassing the context for each behaviour; it removes conditional statements; and it offers a choice of implementations, for example with different time and space trade-offs. GoF adds that code with many conditional statements often shows that Strategy is needed.

The drawbacks are as follows.

  • Clients must know the strategies. The caller has to understand how they differ to pick one, so use the pattern only when the difference matters to the caller.
  • The interface is shared. Some strategies get information they do not use, and simple ones may use none of it.
  • There are more objects. GoF notes that strategies without state can be shared between contexts, and that any state should stay in the context and be passed in at each call.

A good test: if you can name a second, real algorithm, use Strategy. With one algorithm and no sign of another, a plain method is simpler (Level 2, module 7).

Strategy and State (module 3) look the same in code. The difference is who chooses. In Strategy, the client picks the algorithm. In State, the object changes its own behaviour as its situation changes.

Common mistake

Making a strategy for each tiny if. A pattern should replace a real variation, such as fee rules or sort orders, not every branch.

Interview angle

Answer in your head first, then open it.

What is the Strategy pattern?

Each algorithm lives in its own class behind a common interface, and a context holds one and delegates to it. The algorithm can be swapped without changing the context.

Where have you seen it?

Fee rules in a parking lot, payment methods, sorting with Comparator, and routing choices.

How is it different from State?

The client chooses a strategy. A state object changes by itself as the context moves between states.

Check yourself: 1. Name two drawbacks of Strategy from GoF. 2. How do you reduce the number of strategy objects?

Words you will meet

Word Meaning
Strategy One interchangeable algorithm behind a common interface
Context The object that holds a strategy and uses it
Concrete strategy A class that implements one algorithm
Delegate Pass the work to another object
Stateless Holding no data between calls, so it can be shared