mardi 24 juillet 2018

How to instantiate input based strategy pattern

The instantiation of strategy pattern is usually completely overlooked by the examples. Let's assume there is an input that defines which class to use. We'd have something along the lines of:

class Strategy {
    Strategy(){}
    virtual void runAlgorithm() = 0;
};

class A : public Strategy {
    A () {}
    static bool isA(char input){ return input == 'A'; }
    void runAlgorithm { /* Do A algorithm */ }
};

class B : public Strategy {
    B () {}
    static bool isB(char input){ return input == 'B'; }
    void runAlgorithm { /* Do B algorithm */ }
};

// Other algorithms

Strategy* createStrat(char input){
    Strategy* instance;

    // Define which algorithm to use
    if (A::isA(input)) {
        instance = A();
    } else if (B::isB(input)) {
        instance = B();
    } ...

    // Run algorithm
    instance.runAlgorithm();

    return instance;
}

As you can see, if we have multiple different algorithms this if/switch can get pretty big. Is there a pattern to make this code easier to humanly parse (i.e., a for loop and a call) without adding an array of pairs? The question could also be expanded to "How to instantiate an input based strategy pattern?"

Do not limit to this code, as it is just an example.

Aucun commentaire:

Enregistrer un commentaire