The Strategy pattern defines a group of classes that represent a set of possible behaviors. These behaviors can then be used in an application to change its functionality. The Strategy Design Pattern basically decouples an algorithm from its host, and encapsulating the algorithm into a separate class. More simply put, an object and its behaviour are separated and put into two different classes. This allows you to switch the algorithm that you are using at any time.
The following lists the benefits of using the Strategy pattern:
- An alternative to sub classing
- Defines each behavior in its own class, which eliminates conditional statements
- Easier to extend a model to incorporate new behaviors without recoding the application
- It is much simpler to keep track of several different behaviours if each behaviour is a separate class, and not buried in the body of someMethod().
You should use the Strategy pattern when:
- When you have several objects that are basically the same, and differ only in their behaviour, it is a good idea to make use of the Strategy Pattern.
- You need different variants of an algorithm.
- An algorithm uses data unknown to clients.