Search code examples
c++inheritancepolymorphismstrategy-pattern

Strategies with common methods and data structure


I am using C++. I have different classes that are basically strategies for doing the same thing. we have the base class Strategy from which inherit more advanced strategies. each direct or indirect subclass of Strategy has a method run(). An advanced strategy will often call , inside its method run() , the method run() of its parent and then will add some pre or post processing. It might also call it many times, inside a loop.

Now all those strategies are applied on the same DataStruct. Indeed the unique DataStruct is well definied for each strategy. However within each strategy the meaning of DataStruct may not be the same.

Let me give you a simple example: Imagine StrategyA does some optimization over a set A while StrategyAUnionB does optimization over the set A Union B. DataStruct.optimalValue does have a meaning for both but the meaning is not the same.

The easy solution I see now is to put an attribute dataStruct of type DataStruct in the base class and if a strategy will call the run() of a parent class it needs to make a copy of dataStruct that it will use to update dataStruct after the call to run() of the parent class.

I see clearly that this solution is not very clean and I would be grateful if I can get an advice from more experienced programmers.


Solution

  • Since nobody is answering, I will give it a try.

    I would suggest separating the strategy from the data structure. Whenever you invoke a run() of some specific Strategy, you would pass it a DataStruct object (as a reference) to process and update it. And of course, this will extend through your hierarchy of classes. So that the reference will be passed on until the base class and then finally post processed by the starting function.

    This would avoid any ambiguities regarding the meaning of fields in the data structure, since you have to be sure what you mean when you pass it to the function.