feat: Simple Factory

Implement demo for simple factory.
This commit is contained in:
Yuki 2025-04-05 02:11:33 +08:00
parent fa1594968f
commit 91a99e3e25
Signed by: yuki
GPG Key ID: CF40579331C06C73
3 changed files with 52 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
bin
.vscode
a.out

44
01_simple_factory.cpp Normal file
View File

@ -0,0 +1,44 @@
#include <iostream>
#include <memory>
using namespace std;
class Shape {
public:
virtual void draw() = 0;
};
class Circle : public Shape {
public:
virtual void draw() override {
cout << "Circle draw" << endl;
}
};
class Square : public Shape {
public:
virtual void draw() override {
cout << "Square draw" << endl;
}
};
class Factory {
public:
unique_ptr<Shape> generate(const string& s) {
if (s == "circle") {
return make_unique<Circle>();
} else if (s == "square") {
return make_unique<Square>();
}
return nullptr;
}
};
int main() {
Factory f;
unique_ptr<Shape> s = f.generate("circle");
s->draw();
s = f.generate("square");
s->draw();
}

5
notes.md Normal file
View File

@ -0,0 +1,5 @@
# 设计模式笔记
## 简单工厂simple factory
简单工厂将对象的创建过程与使用过程解耦,客户端只需传入参数,而不需要关心创建的细节和具体的子类类型。这样,当需要添加新的产品子类时,只需在工厂中扩展创建逻辑,无需修改客户端代码,从而实现了对变化的封装,提升了系统的可扩展性与可维护性。