CHAPTER 7

image

Strategy Patterns (Or, Policy Patterns)

GoF Definition: Define a family of algorithms, encapsulate each one, and make them interchangeable. The strategy pattern lets the algorithm vary independently from client to client.

Concept

We can select the behavior of an algorithm dynamically at runtime.

Real–Life Example

In a football match, at the last moment, in general, if Team A is leading Team B by a score of 1-0, instead of attacking, Team A becomes defensive. On the other hand, Team B goes for an all-out attack to score.

Computer World Example

The above concept is applicable to a computer football game also. Or, we can think of two dedicated ...

Get Java Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.