请设计一个排队系统,能够让每个进入队伍的用户都能看到自己在队列中所处的位置和变化,队伍可能随时有人加入和退出;当有人退出影响到用户的位置排名时需要及时反馈到用户。
采用观察者模式
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Secretary;
class Client{
public:
Client(int Index,string strName,Secretary *strSub)
{
IndexOfQue=Index;
sub=strSub;
name = strName;
}
void SubInt()
{
IndexOfQue=IndexOfQue-1;
}
void Update();
private:
int IndexOfQue;
string name;
Secretary *sub;
};
class Secretary{
public:
string action;
vector<Client>::iterator it;
void Add(Client ct) { cts.push_back(ct); }
void Remove(int addIndex)
{
if(addIndex >=0 && addIndex < cts.size())
{
for(int i = addIndex; i < cts.size(); i++)
{
cts[i].SubInt();
}
cts.erase(cts.begin() + addIndex-1);
}
}
void Notify()
{
for (it=cts.begin(); it!=cts.end(); ++it)
{
(*it).Update();
}
}
private:
vector<Client> cts;
};
void Client::Update()
{
cout << name << " : your position now is :" << IndexOfQue << " Notify:" << sub->action << endl;
}
void main(){
// 创建通知者
Secretary *p = new Secretary();
// 观察者
Client *c1 = new Client(1,"赵一",p);
Client *c2 = new Client(2,"钱二",p);
Client *c3 = new Client(3,"孙三",p);
Client *c4 = new Client(4,"李四",p);
// 加入通知队列
p->Add(*c1);
p->Add(*c2);
p->Add(*c3);
p->Add(*c4);
//扩展项:设置通知内容
p->action="删除前";
// 通知
p->Notify();
p->action="删除后";
p->Remove(3);
p->Notify();
while(1){} //实现暂停
}