Strat­e­gy is a behav­ioral design pat­tern that lets you define a fam­i­ly of algo­rithms, put each of them into a sep­a­rate class, and make their objects inter­change­able.

Problem: different algorithms exist for a specific task

Solution: the strategy pattern allows to switch between different algorithms at run time based on the context and a policy

Strategy pattern: UML class diagram

Strategy pattern: UML class diagram

image.png

image.png

Structure

image.png

  1. The Con­text main­tains a ref­er­ence to one of the con­crete strate­gies and com­mu­ni­cates with this object only via the strat­e­gy interface.
  2. The Strat­e­gy inter­face is com­mon to all con­crete strate­gies. It declares a method the con­text uses to exe­cute a strategy.
  3. Con­crete Strate­gies imple­ment dif­fer­ent vari­a­tions of an algo­rithm the con­text uses.
  4. The con­text calls the exe­cu­tion method on the linked strat­e­gy object each time it needs to run the algo­rithm. The con­text doesn’t know what type of strat­e­gy it works with or how the algo­rithm is executed.
  5. The Client cre­ates a spe­cif­ic strat­e­gy object and pass­es it to the con­text. The con­text expos­es a set­ter which lets clients replace the strat­e­gy asso­ci­at­ed with the con­text at runtime.”

<aside>

Applicability

<aside>

How to Implement

  1. In the con­text class, iden­ti­fy an algo­rithm that’s prone to fre­quent changes. It may also be a mas­sive con­di­tion­al that selects and exe­cutes a vari­ant of the same algo­rithm at runtime.
  2. Declare the strat­e­gy inter­face com­mon to all vari­ants of the algorithm.
  3. One by one, extract all algo­rithms into their own class­es. They should all imple­ment the strat­e­gy interface.
  4. In the con­text class, add a field for stor­ing a ref­er­ence to a strat­e­gy object. Pro­vide a set­ter for replac­ing val­ues of that field. The con­text should work with the strat­e­gy object only via the strat­e­gy inter­face. The con­text may define an inter­face which lets the strat­e­gy access its data.
  5. Clients of the con­text must as­so­ciate it with a suit­able strat­e­gy that match­es the way they expect the con­text to per­form its pri­ma­ry job.” </aside>