一段自我感觉还不错的代码

CNotify是这样的一个类:

①该类有一个Register接口,可对所有该类及该类的派生类的实例进行注册,注册后的实例均有一个唯一的标识ID

②该类有一个SendNotify接口,可以对指定标识的实例或所有实例发送通知(通知内容为字符串)。

③实例在接收到通知后,都能主动在屏幕上显示自身的标识和该通知。

请设计并实现CNotify类及以上功能。要求不能改动接口。

接口如下:

static void Register(CNotify &rInst);

其中:

rInst为注册的实例。

static void SendNotify(int iType, unsigned int uID, char* pContent);

其中:

iType为指定的发送类型:取值范围为SND_SINGLESND_ALL,分别为指定单个发送或全体发送。

uIDSND_SINGLE时指定的单个发送的实例IDSND_ALL时,该参数无意义。

pContent为发送的通知内容。

 

 

CNotify 作为抽象类,派生出几个类,

CNotifyWorker, 他收到消息之后,老实打印信息

CNotifyLier    他收到消息之后,把消息逆向输出

CNotifyLazyer  他收到消息之后,把消息发送给下一个接受者处理,如果找不到,再自己处理

 

 

#include <iostream>

#include<time.h>
#include<random>
#include<vector>
#include<algorithm>
#include<auto_ptr.h>
usingnamespacestd;

vector<int>systemIdArray;
inttotal=10;
enum{SND_SINGLE=0,SND_ALL=1};

classCNotify{
public:
staticvoidRegister(CNotify&rInst){
if(total--)
{
if(rInst.ID==0)
{
rInst.ID=(unsignedint)&rInst;
systemIdArray.push_back(rInst.ID);
}
else
{
cout<<"have rigister!"<<endl;
}
}
else
{
cout<<"no resource"<<endl;
}
}
staticvoidSendNotify(intiType,unsignedintuID,char*pContent){
if(iType==SND_SINGLE)
{
for(autoi=systemIdArray.begin();i!=systemIdArray.end();i++)
{
if(*i==uID)
{
((CNotify*)uID)->ReciveAction(pContent);
return;
}
}
}else
if(iType==SND_ALL)
{
for(autoi=systemIdArray.begin();i!=systemIdArray.end();i++)
{
if(((CNotify*)(*i))->ID!=0)
{
((CNotify*)(*i))->ReciveAction(pContent);
}
}
return;
}

cout<<"no this ID"<<endl;
}
virtualintReciveAction(char*temp)=0;
public:
intID;
};
classCNotifyWorker:publicCNotify{
public:
CNotifyWorker(){
this->ID=0;
}
virtualintReciveAction(char*temp){
cout<<temp<<endl;
return1;
}
};
classCNotifyLier:publicCNotify{
public:
CNotifyLier(){
this->ID=0;
}
virtualintReciveAction(char*temp){
intlength=sizeof(temp)-1;
do
{
cout<<temp[length];
}while(--length>=0);
cout<<endl;
return1;
}
};
classCNotifyLazyer:publicCNotify{
public:
CNotifyLazyer(){
this->ID=0;
}
virtualintReciveAction(char*temp){
unsignedintId=0;
inti=10;
staticintj=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)
{
return1;
}
}
}

if(i==-1)
{
cout<<temp<<endl;
return1;
}
return0;
}
};
intmain()
{
srand((unsignedint)time(0));
for_each(systemIdArray.begin(),systemIdArray.end(),[](int&x){x=0;});

CNotifyWorkerworker1,worker2;
CNotifyLierlier1,lier2;
CNotifyLazyerlazyer1,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,(unsignedint)&worker1,"haha");
CNotify::SendNotify(SND_SINGLE,(unsignedint)&lier1,"abc");
CNotify::SendNotify(SND_SINGLE,(unsignedint)&lazyer1,"rongshuai");

return0;
}


posted @ 2013-05-03 19:42  javawebsoa  Views(272)  Comments(0)    收藏  举报