I often have a class where I want to allow a functionality to be selected. For example I have a class that has a GetNextNode() function which is used like MyClass::DoIteration(){GetNextNode(); } . I want to allow the user to select from one of many possible implementations of GetNextNode to determine how the next node to process should be determined. I also want to allow a user of my code to easily provide their own implementation.
So far, the answer is to make GetNextNode() virtual and re-implement it subclasses of MyClass…
My problem arises when I have two such interchangeable functions. If I have Function1() and Function2() which both have N possible implementations, then I would have to provide 2N subclasses to allow the user to pick which pair of these functions to use. Generally, it is much worse (if there are more than 2 such functions).
Note that these functions need access to data inside MyClass.
Is there a “pattern” that I am missing that allows “plugins” like this to be selected?
This looks like the Strategy Pattern Edit: And if you only need compile time variations, the Policy-based design you disovered yourself can be more appropriate.
The strategy might need access to other stuff, so you might need to pass in something to GetNextNode, now that the implementation lives in a separte class, and you might want to provide a default implementation of it (e.g. just have MyClass inherit from NextNodeStrategy , and set
nextNode = this; in the MyClass constructor.If you have other things that also can be changed, you make a strategy out of that too, and the 2 can vary independently.