Software developer blog

Event based template method

The last few weeks were more than hectic for me. We are approaching the end of a bigger project, and starting a new one, so I didn't have much time for my blog. Anyhow... during the design phase of the newer project I came across a very interesting design problem. We are developing an algorithm that has a pretty rigid structure at a higher level with steps that are invariable, and other (more heuristic) steps that can vary independently. Since we want to be able to quickly replace the heuristic steps of the algorithm (maybe even at runtime), and have a clean design with as few code duplication as possible I had to come up with a way to decouple these steps from the higher level structure of the algorithm.

The first solution that came to my mind was using the Template Method design pattern as described in the excellent book on Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. While their version comes with many advantages, in this particular situation it has a quite obvious drawback: it uses inheritance, which would make it less convenient to adjust the algorithm, and vary the different heuristic steps independently, and downright impossible to do this at runtime.

I decided to use an event based approach. Instead of defining pure virtual functions for the hooks I defined callbacks similar to events. When the algorithm runs on a callback during execution, it calls the function(s) registered for it. There is however a significant difference between these callbacks and traditional events: in some cases you may want to make sure, that one and only one function is registered for a specific callback, and you may also want to use the return value of the function for something more complex. (Some implementations of event handling require the return value to be a boolean, and use it to prevent further listeners from getting executed when one of the listeners returns false.)

@ //
« Previous Page