Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <vector>
- #include <map>
- using namespace std;
- class Human {
- protected:
- std::string name;
- std::string place;
- public:
- Human() = default;
- Human(const std::string& _name, const std::string& _place):
- name(_name),
- place(_place)
- {}
- virtual void print_info() const = 0;
- };
- class Student : public Human {
- public:
- Student(const std::string& _name, const std::string& _university):
- Human(_name, _university) {}
- void print_info() const override {
- std::cout << name << " studies at " << place << '\n';
- }
- };
- class Teacher : public Human {
- public:
- Teacher(const std::string& _name, const std::string& _school):
- Human(_name, _school) { }
- void print_info() const override {
- std::cout << name << " teaches at " << place << "\n";
- }
- };
- class Programmer : public Human {
- public:
- Programmer(const std::string& _name, const std::string& _company):
- Human(_name, _company) {}
- void print_info() const override {
- std::cout << name << " works at " << place << "\n";
- }
- };
- enum class HumanType {
- student,
- teacher,
- programmer
- };
- class FactoryElementCreator {
- public:
- virtual Human* create(
- const std::string& name,
- const std::string& organization
- ) = 0;
- };
- class StudentCreator : public FactoryElementCreator{
- public:
- Human* create(
- const std::string& name,
- const std::string& organization
- ) override {
- return new Student(name, organization);
- }
- };
- class HumanFactory {
- private:
- map<HumanType, FactoryElementCreator*> creators;
- public:
- template <class T>
- void add(HumanType type) {
- if (creators.count(type)) {
- throw invalid_argument("type already added");
- }
- creators[type] = new T();
- }
- Human* create(
- HumanType type,
- const std::string& name,
- const std::string& organization
- ) {
- auto it = creators.find(type);
- if (it == creators.end()) {
- return nullptr;
- }
- return it->second->create(name, organization);
- }
- ~HumanFactory() {
- for (auto& [type, ptr] : creators) {
- delete ptr;
- }
- }
- };
- int main() {
- HumanFactory factory;
- factory.add<StudentCreator>(HumanType::student);
- auto ptr = factory.create(HumanType::student, "Alex", "HSE");
- if (ptr) {
- ptr->print_info();
- } else {
- std::cout << "not created" << std::endl;
- }
- auto ptr2 = factory.create(HumanType::teacher, "Alex2", "HSE");
- if (ptr2) {
- ptr2->print_info();
- } else {
- std::cout << "not created" << std::endl;
- }
- delete ptr;
- delete ptr2;
- }
Advertisement
Add Comment
Please, Sign In to add comment