1 Star 0 Fork 0

Fingsinz/DesignPatternsInCpp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
main.cpp 1.69 KB
一键复制 编辑 原始数据 按行查看 历史
Fingsinz 提交于 2024-07-21 19:47 . modified 格式
#include <iostream>
#include <memory>
class Sofa {
public:
virtual ~Sofa() = default;
virtual void show() = 0;
};
class ModernSofa : public Sofa {
public:
void show() override {
std::cout << "modern sofa\n";
}
};
class ClassicalSofa : public Sofa {
public:
void show() override {
std::cout << "classical sofa\n";
}
};
class Chair {
public:
virtual ~Chair() = default;
virtual void show() = 0;
};
class ModernChair : public Chair {
public:
void show() override {
std::cout << "modern chair\n";
}
};
class ClassicalChair : public Chair {
public:
void show() override {
std::cout << "classical chair\n";
}
};
class Factory {
public:
virtual ~Factory() = default;
virtual Sofa *createSofa() = 0;
virtual Chair *createChair() = 0;
};
class ModernFactory : public Factory {
public:
Sofa *createSofa() override {
return new ModernSofa();
}
Chair *createChair() override {
return new ModernChair();
}
};
class ClassicalFactory : public Factory {
public:
Sofa *createSofa() override {
return new ClassicalSofa();
}
Chair *createChair() override {
return new ClassicalChair();
}
};
class Orders {
public:
void addOrder(std::string type) {
std::unique_ptr<Factory> factory;
if (type == "modern") {
factory = std::make_unique<ModernFactory>();
} else if (type == "classical") {
factory = std::make_unique<ClassicalFactory>();
}
if (factory) {
std::unique_ptr<Chair> chair(std::move(factory->createChair()));
std::unique_ptr<Sofa> sofa(std::move(factory->createSofa()));
chair->show();
sofa->show();
}
}
};
int main() {
Orders orders;
int n;
std::cin >> n;
while (n--) {
std::string type;
std::cin >> type;
orders.addOrder(type);
}
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

搜索帮助