PDA

View Full Version : broadcasting signals through the application



tuli
28th February 2015, 09:10
Let's say I have a signal that I want to make available to several components of my program throughout the entire project. Let's also say there might be more than one component that might trigger or emit that signal.

Does it make sense to keep a global instance or a singleton of a class that manages such "global" signals?


I mean like this:



class SignalCollection: public QObject
{
Q_OBJECT

void EmitLogMsg(QString msg) {emit sigLogMsg(msg);}
void EmitSettChange() {emit sigSettChange();}

signals:
void sigLogMsg(QString msg);
void sigSettChange();
}


Now receivers from anywhere can connect() to the signals with the SignalCollection as the sender. And senders from anywhere can just call EmitSettChange() from anywhere to emit such a signal.


The advantage is that this breaks up the relation between sender and receiver.


Is that a common pattern? Are there better ways to do this? Or are there any good reasons why I should NOT do that?

d_stranz
28th February 2015, 17:16
You'll first have to make your EmitLogMsg() etc. methods public so other classes can call them, and it would make more sense to make these slots as well so callers can connect their own signals to them. You also need to make a private constructor so you can enforce the singleton rule, and maybe a static getInstance() method that will construct the singleton if needed or return it if already constructed.

The major downside to this is that end receiver of the singleton's signal has no clue where it came from. You've broken the sender() connection by relaying it.

wysota
28th February 2015, 18:34
IMO with the right design the receiver shouldn't care who is the sender of the signal. Such approach promotes loose coupling (which after all is all signals are about).

d_stranz
28th February 2015, 23:05
Yes, that's absolutely true. But it sure helps during debugging when you can arrive at a point from 10 different directions and you'd like to know which one it actually was. Looking at stack traces gets boring after a while.