Design Patterns - Strategy Pattern

Strategy-Image

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.

   
Intent Enables you to use different business rules or algorithms depending on the context in which they occur
Problem The selection of an algorithm that needs to be applied depends on the client making the request or the data being acted on.
Solution Separate the selection of algorithm from the implementation of the algorithm. Allows for the selection to be made based upon context.
Participants and Collaborators Strategy declares an interface common to all supported algorithms, and specifies how the different algorithms are used. Concrete Strategy implements these different algorithms using Strategy interface. Context uses a specific Concrete Strategy with a reference of the type Strategy
Consequences The Strategy pattern defines a family of algorithms. Switch or Conditional can be eliminated

Strategy-pattern-UML

Example

Strategy-pattern-UML