Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
This page is a work in progress
We roll out the updates weekly. Leave your email to track the progress. You can expect one email per month and no spam, pinky promise.
Structure of design pattern
// Common interface for all strategies. interface Strategy is method algorithm(a, b) // Each concrete strategy provides unique implementation. class ConcreteStrategyAdd implements Strategy is method algorithm(a, b) is return a + b class ConcreteStrategySubtract implements Strategy is method algorithm(a, b) is return a - b class ConcreteStrategyMultiply implements Strategy is method algorithm(a, b) is return a * b // Context (as a client) always works with strategies through a common // interface. It does not know or care which strategy is currently active. class Context is private strategy: Strategy method setStrategy(Strategy strategy) is this.strategy = strategy method executeStrategy(int a, int b) is return strategy.execute(a, b) // The concrete strategy is picked on a higher level (for example, by // application config) and passed to the client object. At any time, the // strategy object can be replaced by a different strategy. class ExampleApplication is method main() is Create context object. Read first number Read last number Read the desired action from user input if (action == addition) then context.setStrategy(new ConcreteStrategyAdd()); if (action == subtraction) then context.setStrategy(new ConcreteStrategySubtract()); if (action == multiplication) then context.setStrategy(new ConcreteStrategyMultiply()); result = context.executeStrategy(First number, Second number);