Strategy

  • Define the interface of an interchangeable family of algorithms

  • Bury algorithm implementation details in derived classes

  • Derived classes could be implemented using the Template Method patter

  • Clients of the algorithm couple themselves strictly to the interface

Example - Checking data providers

We are goint to use Strategy pattern to implement various strategies to check websites like Google, eBay and so on.

interface Strategy {
    void solve();
}

class GoogleStrategy implements Strategy {
    @Override
    public void solve() {
        System.out.println("Checking Google");
    }
}

class EbayStrategy implements Strategy {
    @Override
    public void solve() {
        System.out.println("Checking eBay");
    }
}

class StrategyExecutor {
    void execute() {
        Strategy[] strategies = {new GoogleStrategy(), new EbayStrategy()};
        Arrays.stream(strategies).forEach(Strategy::solve);
    }
}

Then we use the executor to run our strategies.

Here is the output.

Using Strategy to replace complex logic in single class

Lets consider we have create a class that is doing a simple thing. It will acquire an item from a storage. Then we did many modification in time and the class become really complex. Such a class is then difficult to modify and test. Also it is difficult to easily get an idea what is the class actually doing.

First indicator that something is wrong is number of parameters in the constructor. Many parameters in the construtor tells us there are too many responsibilities in this class. We need to solve it by moving the code somewhere else. But how do we know what code is supposed to be moved and where?

WIP: Dec 5 2017

Last updated

Was this helpful?