feat: Factory Method

Implemented a demo for the Factory Method.
This commit is contained in:
Yuki 2025-04-05 03:35:19 +08:00
parent 91a99e3e25
commit 91a28ec137
Signed by: yuki
GPG Key ID: CF40579331C06C73
2 changed files with 89 additions and 1 deletions

80
02_factory_method.cpp Normal file
View File

@ -0,0 +1,80 @@
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class Shape {
public:
virtual void draw() = 0;
virtual ~Shape() {};
};
class Circle : public Shape {
int x;
int y;
int r;
public:
Circle(int x, int y, int r) : x(x), y(y), r(r) {}
virtual void draw() {
cout << "draw circle: " << x << " " << y << " " << r << endl;
}
};
class Square : public Shape{
int x1;
int y1;
int x2;
int y2;
public:
Square(int x1, int y1, int x2, int y2) : x1(x1), y1(y1), x2(x2), y2(y2) {}
virtual void draw() {
cout << "draw square: " << x1 << " " << y1 << " " << x2 << " " << y2 << endl;
}
};
class Factory {
public:
virtual unique_ptr<Shape> generate(vector<int>& v) = 0;
};
class SquareFactory : public Factory {
public:
virtual unique_ptr<Shape> generate(vector<int>& v) override {
return make_unique<Square>(v[0], v[1], v[2], v[3]);
}
};
class CircleFactory : public Factory {
public:
virtual unique_ptr<Shape> generate(vector<int>& v) override {
return make_unique<Circle>(v[0], v[1], v[2]);
}
};
// A simple version of Simple Factory
unique_ptr<Factory> choose_factory(string s) {
if (s == "circle") {
return make_unique<CircleFactory>();
} else if (s == "square") {
return make_unique<SquareFactory>();
}
return nullptr;
}
int main() {
auto f = choose_factory("circle");
// Getting factory and generating object is decoupled here.
vector<int> v = {1, 2, 3};
auto s = f->generate(v);
s->draw();
f = choose_factory("square");
v.push_back(4);
s = f->generate(v);
s->draw();
}

View File

@ -1,5 +1,13 @@
# 设计模式笔记 # 设计模式笔记
## 简单工厂(simple factory ## 简单工厂(Simple Factory
简单工厂将对象的创建过程与使用过程解耦,客户端只需传入参数,而不需要关心创建的细节和具体的子类类型。这样,当需要添加新的产品子类时,只需在工厂中扩展创建逻辑,无需修改客户端代码,从而实现了对变化的封装,提升了系统的可扩展性与可维护性。 简单工厂将对象的创建过程与使用过程解耦,客户端只需传入参数,而不需要关心创建的细节和具体的子类类型。这样,当需要添加新的产品子类时,只需在工厂中扩展创建逻辑,无需修改客户端代码,从而实现了对变化的封装,提升了系统的可扩展性与可维护性。
## 工厂模式Factory Method
简单工厂里,我们的输入参数是一样的,如何处理建造时参数不同的情况呢?例如 `Circle` 接受圆心和半径,而 `Square` 接受两个对角的点。
工厂模式给出了解决方案。对于每个新的子类,有一个专门的工厂类生成这个新的子类,进而工厂类可以使用不同的参数构建新的子类。
工厂模式相对简单工厂,通过解耦获取工厂和生成子类实例,获取了更大的灵活性。比如客户端可以在得到工厂后,进一步根据工厂类型向用户请求输入。但是对于一个新类就需要额外需要一个工厂,稍微麻烦些。通过同时使用两种方式,可以达到最大的灵活性。