突然想整理一下自己用过的这个模式,半小时写下了这些代码。
首先定义两个基类,class notifier(发布者) 和 class receiver(订阅者)。
在发布者类中有成员 std::vector<receiver*> observerList,该vector用于存储订阅者对象,当发布者需要发布消息时,消息会被发送给vector中所有的订阅者对象。
在订阅者类中定义 recvMessage(string message)函数,处理从发布者那里得到的消息。
另外,定义了两个子类,genMessage继承自notifier类,getMessage类继承receiver类,并在main.cpp中进行了验证。
代码如下欧:
1)Notifier类:
notifier.h
#ifndef NOTIFIER_H
#define NOTIFIER_H
#include <vector>
#include "receiver.h"
#include <string>
using namespace std;
class notifier
{
public:
notifier();
virtual ~notifier();
void sendToAllRecv(string message);
void loadReceiver(receiver* pRecv);
private:
std::vector<receiver*> observerList;
};
#endif // NOTIFIER_H
notifier.cpp
#include "notifier.h"
notifier::notifier()
{
}
notifier::~notifier()
{
}
void notifier::loadReceiver(receiver* pRecv)
{
observerList.push_back(pRecv);
}
void notifier::sendToAllRecv(string message)
{
std::vector<receiver*>::iterator it = observerList.begin();
for(;it != observerList.end();it++)
{
(*it)->recvMessage(message);
}
}
2)receiver 类
receiver.h
#ifndef RECEIVER_H
#define RECEIVER_H
#include <vector>
#include <string>
#include <iostream>
using namespace std;
class receiver
{
public:
receiver();
~receiver();
virtual void recvMessage(string message) = 0;
};
#endif // RECEIVER_H
receiver.cpp
#include "receiver.h"
receiver::receiver()
{
}
receiver::~receiver()
{
}
//void receiver::recvMessage(string message)
//{
// //printf("Receiver get message: %s \n",message);
// //cout<<message<<"\n";
//}
3)genMessage类
genmessage.h
#ifndef GENMESSAGE_H
#define GENMESSAGE_H
#include "notifier.h"
class genMessage:public notifier
{
public:
genMessage();
~genMessage();
void throwMessage(string str);
};
#endif // GENMESSAGE_H
genmessage.cpp
#include "genmessage.h"
genMessage::genMessage()
{
}
genMessage::~genMessage()
{
}
void genMessage::throwMessage(string str)
{
sendToAllRecv(str);//基类的函数
}
4) getmessage类
getmessage.h
#ifndef GETMESSAGE_H
#define GETMESSAGE_H
#include "receiver.h"
class getMessage:public receiver
{
public:
getMessage();
~getMessage();
void recvMessage(string message);
};
#endif // GETMESSAGE_H
getmessage.cpp
#include "getmessage.h"
getMessage::getMessage()
{
}
getMessage::~getMessage()
{
}
void getMessage::recvMessage(string message)
{
cout<<"one receiver receive:"<<message<<endl;
}
5) main.cpp
#include <iostream>
#include <vector>
#include "getmessage.h"
#include "genmessage.h"
using namespace std;
int main()
{
cout << "Hello World!" << endl;
/
genMessage notifier1;
getMessage receiver1;
getMessage receiver2;
notifier1.loadReceiver(&receiver1);
notifier1.loadReceiver(&receiver2);
notifier1.sendToAllRecv("here it is");
getchar();
return 0;
}