CNotify是这样的一个类:
①该类有一个Register接口,可对所有该类及该类的派生类的实例进行注册,注册后的实例均有一个唯一的标识ID。
②该类有一个SendNotify接口,可以对指定标识的实例或所有实例发送通知(通知内容为字符串)。
③实例在接收到通知后,都能主动在屏幕上显示自身的标识和该通知。
请设计并实现CNotify类及以上功能。要求不能改动接口。
接口如下:
static void Register(CNotify &rInst);
其中:
rInst为注册的实例。
static void SendNotify(int iType, unsigned int uID, char* pContent);
其中:
iType为指定的发送类型:取值范围为SND_SINGLE和SND_ALL,分别为指定单个发送或全体发送。
uID为SND_SINGLE时指定的单个发送的实例ID,SND_ALL时,该参数无意义。
pContent为发送的通知内容。
CNotify 作为抽象类,派生出几个类,
CNotifyWorker, 他收到消息之后,老实打印信息
CNotifyLier 他收到消息之后,把消息逆向输出
CNotifyLazyer 他收到消息之后,把消息发送给下一个接受者处理,如果找不到,再自己处理
#include <iostream>
#include <time.h>
#include <random>
#include <vector>
#include <algorithm>
#include <auto_ptr.h>
using namespace std;
vector<int> systemIdArray;
int total = 10;
enum{SND_SINGLE = 0,SND_ALL = 1};
class CNotify{
public:
static void Register(CNotify &rInst){
if(total--)
{
if(rInst.ID == 0)
{
rInst.ID = (unsigned int)&rInst;
systemIdArray.push_back(rInst.ID);
}
else
{
cout<<"have rigister!"<<endl;
}
}
else
{
cout<<"no resource"<<endl;
}
}
static void SendNotify(int iType, unsigned int uID, char* pContent){
if(iType == SND_SINGLE)
{
for(auto i = systemIdArray.begin();i != systemIdArray.end();i++)
{
if(*i == uID)
{
((CNotify *)uID)->ReciveAction(pContent);
return ;
}
}
}else
if(iType == SND_ALL)
{
for(auto i = systemIdArray.begin();i != systemIdArray.end();i++)
{
if(((CNotify *)(*i))->ID != 0)
{
((CNotify *)(*i))->ReciveAction(pContent);
}
}
return ;
}
cout<<"no this ID"<<endl;
}
virtual int ReciveAction(char *temp)=0;
public:
int ID;
};
class CNotifyWorker:public CNotify{
public:
CNotifyWorker(){
this->ID = 0;
}
virtual int ReciveAction(char *temp){
cout<<temp<<endl;
return 1;
}
};
class CNotifyLier :public CNotify{
public:
CNotifyLier(){
this->ID = 0;
}
virtual int ReciveAction(char *temp){
int length = sizeof(temp)-1;
do
{
cout<<temp[length];
}while(--length >= 0);
cout<<endl;
return 1;
}
};
class CNotifyLazyer:public CNotify{
public:
CNotifyLazyer(){
this->ID = 0;
}
virtual int ReciveAction(char *temp){
unsigned int Id = 0;
int i = 10;
static int j = 0;
while(--i >= 0)
{
Id = systemIdArray.at(j);
if(Id == 0)
continue;
else
if(((CNotify *)Id)->ID != 0)
{
j++;
if( ((CNotify *)Id)->ReciveAction(temp) == 1)
{
return 1;
}
}
}
if(i == -1)
{
cout<<temp<<endl;
return 1;
}
return 0;
}
};
int main()
{
srand((unsigned int)time(0));
for_each(systemIdArray.begin(),systemIdArray.end(),[](int& x){x = 0;});
CNotifyWorker worker1,worker2;
CNotifyLier lier1,lier2;
CNotifyLazyer lazyer1,lazyer2,lazyer3;
CNotify::Register(lazyer3);
CNotify::Register(worker1);
CNotify::Register(worker2);
CNotify::Register(lier1);
CNotify::Register(lier2);
CNotify::Register(lazyer1);
CNotify::Register(lazyer2);
CNotify::SendNotify(SND_SINGLE,(unsigned int)&worker1,"haha");
CNotify::SendNotify(SND_SINGLE,(unsigned int)&lier1,"abc");
CNotify::SendNotify(SND_SINGLE,(unsigned int)&lazyer1,"rongshuai");
return 0;
}