【设计模式】观察者模式

举例:

小王借了好多钱,分别问boss1,boss2,boss3借钱,但是小王暂时没有能力还钱,如果小王有钱的话,就会通知债主,让债主来要钱。

类的实现

c 复制代码
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函数

}
c 复制代码
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;

}
c 复制代码
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;

}



};
c 复制代码
int main()
{
  xiaowang x1;
  boss1 x2;
  boss2 x3;
  boss3 x4;
  x1.Borrow(&x1);
  x1.Borrow(&x2);
  x1.Borrow(&x3);
  x1.notifyallcreditor();

}

完整代码:

c 复制代码
#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();

}
相关推荐
Navigator_Z11 分钟前
LeetCode //C - 1269. Number of Ways to Stay in the Same Place After Some Steps
c语言·算法·leetcode
2601_9657422214 分钟前
短视频脚本创作方法分享:本地生活类账号的起步思路
大数据·人工智能·算法·ai·新媒体运营·生活
55873生态系统手记22 分钟前
读完 55873 资产钱包的技术栈,我重新理解了 "合规钱包" 应该长什么样
算法·架构
旋生万物25 分钟前
素数螺旋映射 $z_n=n^{1+i}$ 的角分布统计检验与零模型对比
大数据·前端·人工智能·算法·云原生·螺旋生成论·螺旋相位
HRTOS27 分钟前
HRTOS Shell继续完善:优化printf缓冲区与字符串越界保护,国庆后随新版本更新
运维·单片机·嵌入式硬件·算法·51单片机
邵奈一1 小时前
当沉香之乡遇上 Seed-2.1-pro:我用 AI 给村子做了一个数字门面
算法·架构
海天一色y1 小时前
图像分割全解析:从经典算法到深度学习的原理与实战(Python + MATLAB)
python·深度学习·算法
垆边人似月.1 小时前
华为算法题:最长连续递增子序列的变
数据结构·算法·leetcode
YOLO数据集集合1 小时前
机器学习二分类预测算法组合工具:12种算法、113种组合的批量建模方案8031期
算法·机器学习
longlongzihan2 小时前
LeetCode 56合并区间:排序与贪心
c++·算法·leetcode