Исправь данный код на языке C++: main.cpp: #include “library.h” #include “log.h” int…
- User
Исправь данный код на языке C++: main.cpp:
#include “library.h” #include “log.h”
int main() { // Использование паттерна factory и prototype ShapeFactory shapeFactory;
codeshapeFactory.registerShape(“circle”, new Circle()); shapeFactory.registerShape(“rectangle”, new Rectangle()); shapeFactory.registerShape(“triangle”, new Triangle()); Shape* circle1 = shapeFactory.createShape(“circle”); Shape* circle2 = shapeFactory.createShape(“circle”); Shape* rectangle1 = shapeFactory.createShape(“rectangle”); if (circle1) { circle1->draw(); delete circle1; } if (circle2) { circle2->draw(); delete circle2; } if (rectangle1) { rectangle1->draw(); delete rectangle1; } // Использование паттерна singleton Log& log = Log::getInstance(); log.writeLog(“User created a circle”); log.writeLog(“User created a circle”); log.writeLog(“User created a rectangle”); return 0;}
library.cpp:
#include “library.h”
Shape* ShapeFactory::createShape(const std::string& name) { if (shapes.find(name) != shapes.end()) { Shape* shape = shapes[name]->clone(); if (shape) { return shape; } else { return nullptr; } } else { return nullptr; } }
void ShapeFactory::registerShape(const std::string& name, Shape* shape) { shapes[name] = shape; }
Shape* Circle::clone() { return new Circle(); }
Shape* Rectangle::clone() { return new Rectangle(); }
Shape* Triangle::clone() { return new Triangle(); }
log.cpp:
#include “log.h”
Log::Log() { logFile.open(“log.txt”); }
Log& Log::getInstance() { static Log instance; return instance; }
void Log::writeLog(const std::string& message) { logFile << message << std::endl; }
Затем создаем соответствующие заголовочные файлы для каждого cpp файла:
library.h:
#ifndef LIBRARY_H #define LIBRARY_H
#include #include <unordered_map>
// Прототип базовой графической фигуры class Shape { public: virtual void draw() = 0; virtual Shape* clone() = 0; virtual ~Shape() {} };
// Конкретная базовая фигура - Круг class Circle : public Shape { public: void draw() override;
- Assistant
main.cpp:
#include "library.h" #include "log.h"
int main() { // Использование паттерна factory и prototype ShapeFactory shapeFactory;
code