前言
我觉得这是最有意思的模式,其中一个动,另外的自动跟着动。发布-订阅,我觉得很巧妙。
代码
头文件
cpp
#pragma once
#include<vector>
#include<string>
#include<iostream>
// 抽象观察者
class Aobserver
{
public:
virtual void update(std::string& updated_state) = 0;
};
// 抽象通知者
class Asubject
{
protected:
std::vector<Aobserver*> _pObservers;
bool whetherRegist(Aobserver* p_observer)
{
for (auto it : _pObservers) {
if (it == p_observer) return true;
}
return false;
}
public:
virtual void registObserver(Aobserver* p_observer) = 0;
virtual void detachObserver(Aobserver* p_observer) = 0;
virtual void notify(const std::string& teacher_name) = 0;
};
// 具体通知者
class Csubject1 : public Asubject
{
private:
std::string _subjectName;
public:
Csubject1(const std::string& subject_name) :_subjectName(subject_name) {}
// 注册观察者
void registObserver(Aobserver* p_observer) override
{
if (p_observer!=nullptr && whetherRegist(p_observer) == false) {
_pObservers.push_back(p_observer);
}
}
void detachObserver(Aobserver* p_observer) override
{
if (p_observer != nullptr)
{
for (auto it : _pObservers) {
if (it == p_observer) {
_pObservers.erase(
std::remove(_pObservers.begin(),_pObservers.end(),it),
_pObservers.end());
}
}
}
}
void notify(const std::string& teacher_name) override
{
std::string notify_state = _subjectName + " say: "+ teacher_name +" is coming!";
for (auto it : _pObservers) {
it->update(notify_state);
}
}
};
// 具体观察者
class Hablee : public Aobserver
{
private:
void cancleReading(std::string& updated_state)
{
std::cout << updated_state;
std::cout << " you should stop reading" << std::endl;
}
public:
void update(std::string& updated_state) override
{
this->cancleReading(updated_state);
}
};
class Yuki : public Aobserver
{
private:
void canclePlayingGuitar(std::string& updated_state)
{
std::cout << updated_state;
std::cout << " you should stop plaing guitar" << std::endl;
}
public:
void update(std::string& updated_state) override
{
this->canclePlayingGuitar(updated_state);
}
};
main.cpp
cpp
#include<iostream>
#include"Aobserver.h"
int main()
{
Csubject1 wzq("wangZhaoQi"); // 通知者
Hablee lhb;
wzq.registObserver(&lhb);
Yuki wwy;
wzq.registObserver(&wwy);
wzq.notify("lyj");
wzq.notify("xiaoZhang");
wzq.detachObserver(&lhb);
wzq.notify("lyj");
return 0;
}