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;
};
开发者_JAVA百科
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.
You are right on with this approach. Yes this is the essence of the strategy pattern..."Vary the algorithm independent of the implementation." You can just give yourself a generic constructor to pass in the parameters you need to initialize your class, such as an object array.
Enjoy!
Strategy pattern are useful when you want to decide on runtime which algorithm to be used.
You could also pass parameters in using a single interface of a memory block containing key-value pairs. That way the interface is common between any present and future algorithms. Each algorithm implementation would know how to decode the key-value pairs into its parameters.
IMHO, you are facing the challenge as you are confusing between the creational aspect of the concrete algorithm and the actual running of the algorithm. As long as the 'DoSomething'
interface remains the same, Strategy Pattern
can be used. It is only the creation of the different concrete algorithm that varies in your case, which can be handled through a Factory Method
design pattern.
精彩评论