Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strategy pattern executing two or more algorithms

Can anyone make me an example of a strategy pattern that use not one, but two or more algorithms in sequence??

Maybe have I to insert those algorithms in a list and then with a for execute all algorithms in this list?

This list must be a public attribute of context class?

Please, can anyone make me a pseudo-code example?

like image 818
user1993478 Avatar asked Sep 20 '26 07:09

user1993478


1 Answers

You could implement a strategy, which invokes all algorithms in specific order. My example is linked with classes described in Strategy pattern:

class MultiAlgorithm implements Strategy {

    private Strategy[] strategies;

    public MultiAlgorithm(Strategy... strategies) {
        if (strategies == null || strategies.length == 0) {
            throw new IllegalArgumentException(
                    "Algorithms collection cann't be null!");
        }
        this.strategies = strategies;
    }

    @Override
    public int execute(int a, int b) {
        System.out.println("Called MultiAlgorithm's execute()");
        int result = 0;
        for (Strategy strategy : strategies) {
            result += strategy.execute(a, b);
        }
        return result;
    }
}

Example of usage

public static void main(String[] args) throws Exception {
    Context context = new Context(new MultiAlgorithm(new Add(),
            new Multiply(), new Subtract()));
    int result = context.executeStrategy(1, 2);
    System.out.println(result);
}

As you see, we must only implement new "complicated strategy". Pattern himself stayed without changes.

like image 67
Michał Ziober Avatar answered Sep 21 '26 20:09

Michał Ziober



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!