Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which design pattern is most appropriate?

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;   
};
like image 521
Umbungu Avatar asked Jun 02 '10 20:06

Umbungu


2 Answers

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.

like image 59
Otávio Décio Avatar answered Sep 23 '22 20:09

Otávio Décio


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.

like image 22
Nikko Avatar answered Sep 21 '22 20:09

Nikko