[C++]【笔记】观察者模式
代码编译环境:VS2019来一波热心吧!鼓励一下新人,谢谢
#include <iostream>
#include <list>
using namespacestd;
//博客
class CBlog
{
public:
CBlog(string strName)
{
m_strName = strName;
}
public:
string m_strName;
string m_strConnext;
};
//观察者
class IObserver
{
public:
virtual void Notify(CBlog* pBlg) = 0;
};
//用户 1:N
class CPerson:public IObserver
{
public:
CPerson(string strName)
{
m_strName = strName;
}
void AddPerson(IObserver* pObj)
{
m_lstObj.push_front(pObj);
}
void SendConnext(string strConnext)
{
CBlog* pBlg = new CBlog(m_strName);
pBlg->m_strConnext = strConnext;
//遍历好友列表,调用回复
auto it = m_lstObj.begin();
while (it!=m_lstObj.end())
{
(*it)->Notify(pBlg);
++it;
}
}
//重写接口收到Notify通知
void Notify(CBlog* pBlg)
{
cout << "收到用户Notify:" << pBlg->m_strName <<pBlg->m_strConnext << endl;
}
public:
string m_strName;
string m_strConnext;
list<IObserver*> m_lstObj;
list<CBlog*> m_lstBlg;
};
int main()
{
std::cout << "Hello World!\n";
//创建用户
CPerson* p1 = new CPerson("战士");
CPerson* p2 = new CPerson("法师");
CPerson* p3 = new CPerson("道士");
//加好友
p1->AddPerson(p2);
p1->AddPerson(p3);
//p1说话
p1->SendConnext("打BOSS!!");
}
感谢楼主分享 感谢分享!!!!!!!!! 感谢楼主分享 感谢楼主分享 支持一波!! 你管这叫新人????? 感谢分享,正好计划准备研究C++
页:
[1]