Define a family of algorithms, encapsulate each one, and make them interchangeable.The Strategy pattern consists of a family of related algorithms behind a driver class called the Context. Either the client or the context select the which one of the algorithms to use for the given situation. The strategy pattern may be used in the following scenarios:
Strategy lets the algorithm vary independently from clients that use it.
- When you have many related classes that differ only in behavior. Strategy pattern provides a way to configure a class with one of many behaviors.
- Strategy pattern can be used when you have different variants of an algorithm. Each variant can be encapsulated within a strategy.
- An algorithm uses internal data structures that need not be exposed to the client.
- A class defines many behaviors, which are selected by multiple conditional statements. Eliminate conditional statements by encapsulating each behaviour in a strategy.
- Hierarchies of Strategy classes can be used to define a family of algorithms or behaviors for contexts to reuse.
- Encapsulating the algorithm in separate Strategy classes lets you vary the algorithm independently of its context.
- The Strategy pattern offers an alternative to conditional statements for selecting desired behavior. When different behaviors are Encapsulating different behaviours in different Strategy classes eliminates the need for conditional statements.
- A client must understand how Strategies differ to be able to select the right strategy. If possible, the context may be albe to this for you.
- Strategy pattern increases the number of objects in an application.