diff --git a/02_factory_method.cpp b/02_factory_method.cpp new file mode 100644 index 0000000..54b0a56 --- /dev/null +++ b/02_factory_method.cpp @@ -0,0 +1,80 @@ +#include +#include +#include + +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 generate(vector& v) = 0; +}; + +class SquareFactory : public Factory { +public: + virtual unique_ptr generate(vector& v) override { + return make_unique(v[0], v[1], v[2], v[3]); + } +}; + +class CircleFactory : public Factory { +public: + virtual unique_ptr generate(vector& v) override { + return make_unique(v[0], v[1], v[2]); + } +}; + +// A simple version of Simple Factory +unique_ptr choose_factory(string s) { + if (s == "circle") { + return make_unique(); + } else if (s == "square") { + return make_unique(); + } + + return nullptr; +} + +int main() { + auto f = choose_factory("circle"); + // Getting factory and generating object is decoupled here. + vector 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(); +} \ No newline at end of file diff --git a/notes.md b/notes.md index f5142e8..8aab762 100644 --- a/notes.md +++ b/notes.md @@ -1,5 +1,13 @@ # 设计模式笔记 -## 简单工厂(simple factory) +## 简单工厂(Simple Factory) 简单工厂将对象的创建过程与使用过程解耦,客户端只需传入参数,而不需要关心创建的细节和具体的子类类型。这样,当需要添加新的产品子类时,只需在工厂中扩展创建逻辑,无需修改客户端代码,从而实现了对变化的封装,提升了系统的可扩展性与可维护性。 + +## 工厂模式(Factory Method) + +简单工厂里,我们的输入参数是一样的,如何处理建造时参数不同的情况呢?例如 `Circle` 接受圆心和半径,而 `Square` 接受两个对角的点。 + +工厂模式给出了解决方案。对于每个新的子类,有一个专门的工厂类生成这个新的子类,进而工厂类可以使用不同的参数构建新的子类。 + +工厂模式相对简单工厂,通过解耦获取工厂和生成子类实例,获取了更大的灵活性。比如客户端可以在得到工厂后,进一步根据工厂类型向用户请求输入。但是对于一个新类就需要额外需要一个工厂,稍微麻烦些。通过同时使用两种方式,可以达到最大的灵活性。