C++ Design – Communication Between State Machine and GUI

cdesignobject-oriented-design

I am writing a finite state machine in C++, designed as a library.
Furthermore, I have a GUI implemented as a separate project which needs to update the user interface according to state changes happening in the library.

The way I implement the communication now, is that the GUI is calling a library function which returns a struct containing information about the state of the finite state machine (and other necessary information).

But I find this a rather ad-hoc solution and since it seems like a frequent situation, I am curious to know if there is a design pattern / text book way of handling this.

Best Answer

The simplest method is to pass a callback function to the state machine that gets called when a state changes (or other event happens).

Then when it gets called you can update the gui in that function (or forward the message to the gui thread if the state machine runs in a separate thread).

The signature would be something like void callback(State oldstate, State newstate, void* userData)

The userData pointer is supplied at the same time as the function pointer and provides a context for the (static) callback function. If you want you can also use a std::function instead and keep the function pointer+userData method as overload.

Related Topic