1 Star 0 Fork 0

Fingsinz/DesignPatternsInCpp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
main.cpp 1.93 KB
一键复制 编辑 原始数据 按行查看 历史
Fingsinz 提交于 2024-07-29 15:25 . added 观察者模式
#include <iostream>
#include <memory>
#include <vector>
class Observer {
public:
Observer(std::string name = "")
: m_name(name) {}
virtual ~Observer() = default;
virtual void update(int time) = 0;
protected:
std::string m_name;
};
class Student : public Observer {
public:
Student(std::string name = "")
: Observer(name) {}
void update(int time) override {
std::cout << m_name << " " << time << std::endl;
}
};
class Subject {
public:
virtual ~Subject() = default;
virtual void registerObserver(Observer *observer) = 0;
virtual void removeObserver(Observer *observer) = 0;
virtual void notifyObserver() = 0;
virtual void setTime() = 0;
};
class Clock : public Subject {
public:
void registerObserver(Observer *observer) override {
std::unique_ptr<Observer> ptr(observer);
observers.push_back(std::move(ptr));
}
void removeObserver(Observer *observer) override {
for (auto it = observers.begin(); it != observers.end(); it++) {
if (it->get() == observer) {
observers.erase(it);
break;
}
}
}
void notifyObserver() override {
for (auto &observer : observers) {
observer->update(m_time);
}
}
void setTime() override {
m_time += 1;
if (m_time == 24) {
m_time = 0;
}
notifyObserver();
}
private:
std::vector<std::unique_ptr<Observer>> observers;
int m_time = 0;
};
int main() {
std::unique_ptr<Subject> clock = std::make_unique<Clock>();
int numOfStudent;
std::cin >> numOfStudent;
while (numOfStudent--) {
std::string name;
std::cin >> name;
Observer *stu = new Student(name);
clock->registerObserver(stu);
}
int updateTimes;
std::cin >> updateTimes;
while (updateTimes--) {
clock->setTime();
}
return 0;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/fingsinz/design-patterns-in-cpp.git
git@gitee.com:fingsinz/design-patterns-in-cpp.git
fingsinz
design-patterns-in-cpp
DesignPatternsInCpp
master

搜索帮助