举例:
小王借了好多钱,分别问boss1,boss2,boss3借钱,但是小王暂时没有能力还钱,如果小王有钱的话,就会通知债主,让债主来要钱。
类的实现
class Creditor//债主类
{
public:
virtual void takemoney()=0;
virtual ~Creditor();
};
class debtor
{
public:
virtual ~debtor();
virtual void Borrow(Creditor*cred)=0;
virtual void notifyallcreditor()=0;//通知债主使用takemoney函数
}
class xiaowang: public debtor
{
public:
void Borrow(Creditor*cred)override//问谁借钱了,就把他记录下来
{
allcreaditor.push_back(cred);
}
void notifyallcreditor()override//通知债主要钱
{
for(auto e:allcreaditor)
{
e->takemoney();
}
}
vector<Creditor*>allcreaditor;
}
class boss1:public Creditor
{
public:
void takemoney()override
{
cout<<"boss 1要钱"<<endl;
}
};
class boss2:public Creditor
{
public:
void takemoney()override
{
cout<<"boss 2要钱"<<endl;
}
};
class boss3:public Creditor
{
public:
void takemoney()override
{
cout<<"boss 3要钱"<<endl;
}
};
int main()
{
xiaowang x1;
boss1 x2;
boss2 x3;
boss3 x4;
x1.Borrow(&x1);
x1.Borrow(&x2);
x1.Borrow(&x3);
x1.notifyallcreditor();
}
完整代码:
#include<iostream>
#include "vector"
using namespace std;
class Creditor
{
public:
virtual void takemoney()=0;
virtual ~Creditor(){};
};
class debtor
{
public:
virtual ~debtor(){};
virtual void Borrow(Creditor*cred)=0;
virtual void notifyallcreditor()=0;
};
class xiaowang: public debtor
{
public:
void Borrow(Creditor*cred)override
{
allcreaditor.push_back(cred);
}
void notifyallcreditor()override
{
for(auto e:allcreaditor)
{
e->takemoney();
}
}
private:
vector<Creditor*> allcreaditor;
};
class boss1:public Creditor
{
public:
void takemoney()override
{
cout<<"boss 1要钱"<<endl;
}
};
class boss2:public Creditor
{
public:
void takemoney()override
{
cout<<"boss 2要钱"<<endl;
}
};
class boss3:public Creditor
{
public:
void takemoney()override
{
cout<<"boss 3要钱"<<endl;
}
};
int main()
{
xiaowang x1;
boss1 x2;
boss2 x3;
boss3 x4;
x1.Borrow(&x2);
x1.Borrow(&x3);
x1.Borrow(&x4);
x1.notifyallcreditor();
}