Strategy

Intent

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

Structure of design pattern

Strategy pattern structure

Pseudocode

// 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);

Implementations in Different Programming Languages

Java