Which design template is most suitable?

I want to create a class that can use one of four algorithms (and the algorithm used is known only at runtime). I thought the strategy design template sounds appropriate, but my problem is that each algorithm requires several different parameters. It would be a bad design to use a strategy, but pass the appropriate parameters to 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, eg 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; }; 
+6
c ++ inheritance design-patterns strategy-pattern
source share
6 answers

This would be the right design, because the Strategy template requires an interface definition, and any class that implements it is a valid candidate for running strategy code, no matter how it is built.

+7
source share

I think that this is correct if you have all the parameters you need when you create a new strategy, and what you do is clear to everyone who reads the code.

+2
source share

You are right with this approach. Yes, this is the essence of the strategy template ... "Change the implementation-independent algorithm." . You can simply give yourself a generic constructor to pass in the parameters needed to initialize your class, such as an array of objects.

Enjoy it!

+2
source share

The strategic pattern is useful when you want to determine the runtime, which algorithm will be used.

+1
source share

You can also pass parameters when using a single memory block interface containing key-value pairs. Thus, the interface is common to any existing and future algorithms. Each implementation of the algorithm will know how to decode key-value pairs into its parameters.

0
source share

IMHO, you are faced with a problem, because you are mixing the creative aspect of a particular algorithm and the actual course of the algorithm. As long as the 'DoSomething' interface remains the same, you can use the Strategy Pattern . In your case, only a specific concrete algorithm can be created that can be processed using the Factory Method design pattern.

0
source share

All Articles