I want to create a class that can use one of four algorithms (and the algorithm to use is only known at run-time). I was thinking that the Strategy design pattern sounds appropriate, but my problem is that each algorithm requires slightly different parameters. Would it be a bad design to use strategy, but pass in the relevant parameters into the constructor?.
Here is an example (for simplicity, let's say there are only two possible algorithms) ...
class Foo
{
private:
// At run-time the correct algorithm is used, e.g. a = new Algorithm1(1);
AlgorithmInterface* a;
};
class AlgorithmInterface
{
public:
virtual void DoSomething() = 0;
};
class Algorithm1 : public AlgorithmInterface
{
public:
Algorithm1( int i ) : value(i) {}
virtual void DoSomething(){ // Does something with int value };
int value;
};
class Algorithm2 : public AlgorithmInterface
{
public:
Algorithm2( bool b ) : value(b) {}
virtual void DoSomething(){ // Do something with bool value };
bool value;
};
It would be a valid design because the Strategy pattern asks for an interface to be defined and any class that implements it is a valid candidate to run the strategy code, regardless how it is constructed.
I think it's correct, if you have all the parameters you need when you create the new strategy and what you do is clear for everyone reading the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With