Which design pattern is most appropriate?

Posted by Anon on Stack Overflow See other posts from Stack Overflow or by Anon
Published on 2010-06-02T20:40:02Z Indexed on 2010/06/02 20:44 UTC
Read the original article Hit count: 272

Hello,

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;   
};

© Stack Overflow or respective owner

Related posts about c++

Related posts about design-patterns