broadcast.h
#ifndef BROADCAST_H
#define BROADCAST_H
#include <QObject>
#include <QMap>
typedef void (*BroadcastBack)();//声明函数指针类型
class Broadcast: public QObject {
Q_OBJECT
public:
static Broadcast& getInstance(){
static Broadcast instance;
return instance;
}
void addListener(QString action,BroadcastBack broadcastBack);
void sendMessage(QString action);
private:
Broadcast();
Broadcast(const Broadcast&){}
Broadcast& operator==(const Broadcast&){}
QMap<QString,BroadcastBack> mBackMap;
signals:
void signalMessage(QString action);
private slots:
void slotMessage(QString action);
};
#endif // BROADCAST_H
broadcast.cpp
#include "broadcast.h"
Broadcast::Broadcast(){
connect(this,SIGNAL(signalMessage(QString)),this,SLOT(slotMessage(QString)));
}
void Broadcast::slotMessage(QString action){
BroadcastBack broadcastBack= this->mBackMap.find(action).value();
if(broadcastBack!=NULL){
broadcastBack();
}
}
void Broadcast::addListener(QString action,BroadcastBack broadcastBack){
this->mBackMap.insert(action,broadcastBack);
}
void Broadcast::sendMessage(QString action){
emit signalMessage(action);
}
使用:
Broadcast::getInstance().addListener("REFRESH_IOT_HOME_VIEW",[]{
qDebug("====REFRESH_IOT_HOME_VIEW====");
});
Broadcast:: getInstance(). sendMessage("REFRESH_IOT_HOME_VIEW");