Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Strategy Design Pattern, making an interface array

After having implemented the strategy pattern, I wanted to make an array of the interface-type, to which I can then add any concrete type.

For those who don't know the strategy pattern: http://en.wikipedia.org/wiki/Strategy_pattern In this particular example I would want to make a StrategyInterface array, which I can then fill with concrete type's A, B and C. However, because this is an abstract class, I can't get it done. Is there a way to do this, or is it completely impossible, without removing the abstract method?

like image 458
user23163 Avatar asked Dec 30 '22 09:12

user23163


2 Answers

Make the array store pointers to the interface type:

typedef std::vector<Interface *> Array;
Array myArray;
myArray.push_back(new A());

Additionally, you can use ptr_vector which manages memory for you:

typedef boost::ptr_vector<Interface> Array;
// the rest is the same
like image 116
1800 INFORMATION Avatar answered Jan 05 '23 16:01

1800 INFORMATION


store pointers not objects..... use boost::shared_ptr if you are wanting to store objects.

like image 26
Keith Nicholas Avatar answered Jan 05 '23 15:01

Keith Nicholas