/
nanezz
/
pov2
Обзор
Документация
Войти
/
nanezz
/
pov2
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
pov2.cpp
138 строк
3 KB
nanezz
Create: pov2.cpp, pov2.slnx, error_log.txt, fatal_log.txt
07 авг 2026, 23:04
Верифицирован
07 авг 2026, 23:04
f599fab
Код
Авторство
О чём код?
#include <iostream> #include <fstream> #include <string> #include <vector> #include <memory> class Observer { public: virtual ~Observer() = default; virtual void onWarning(const std::string& message) {} virtual void onError(const std::string& message) {} virtual void onFatalError(const std::string& message) {} }; class Observable { private: mutable std::vector<std::weak_ptr<Observer>> observers; void cleanExpired() const { auto it = std::remove_if( observers.begin(), observers.end(), [](const std::weak_ptr<Observer>& w) { return w.expired(); } ); observers.erase(it, observers.end()); } public: void addObserver(std::shared_ptr<Observer> obs) { observers.push_back(obs); } void warning(const std::string& message) const { cleanExpired(); for (const auto& w : observers) { if (auto obs = w.lock()) { obs->onWarning(message); } } } void error(const std::string& message) const { cleanExpired(); for (const auto& w : observers) { if (auto obs = w.lock()) { obs->onError(message); } } } void fatalError(const std::string& message) const { cleanExpired(); for (const auto& w : observers) { if (auto obs = w.lock()) { obs->onFatalError(message); } } } }; class WarningObserver : public Observer { public: void onWarning(const std::string& message) override { std::cout << "WARNING: " << message << std::endl; } }; class ErrorObserver : public Observer { private: std::string filePath; public: ErrorObserver(const std::string& path) : filePath(path) {} void onError(const std::string& message) override { std::ofstream file(filePath, std::ios::app); if (file.is_open()) { file << "ERROR: " << message << std::endl; } } }; class FatalErrorObserver : public Observer { private: std::string filePath; public: FatalErrorObserver(const std::string& path) : filePath(path) {} void onFatalError(const std::string& message) override { std::cout << "FATAL: " << message << std::endl; std::ofstream file(filePath, std::ios::app); if (file.is_open()) { file << "FATAL: " << message << std::endl; } } }; int main() { Observable observable; auto warningObs = std::make_shared<WarningObserver>(); auto errorObs = std::make_shared<ErrorObserver>("error_log.txt"); auto fatalObs = std::make_shared<FatalErrorObserver>("fatal_log.txt"); observable.addObserver(warningObs); observable.addObserver(errorObs); observable.addObserver(fatalObs); observable.warning("Low disk space"); observable.error("Connection lost"); observable.fatalError("System crash"); return 0; }