3D几何库解耦Creator类API设计咨询:适配多签名构造
问题背景
我开发了一个3D几何库,包含Point、Vector、Axis、LinePiece、Plane等类,所有类均继承自GeometryObject类:
class Point : public GeometryObject; class Vector : public GeometryObject; class Axis : public GeometryObject; class LinePiece : public GeometryObject; class Plane : public GeometryObject;
构造函数设计
每个类都有多个构造函数,示例如下:
Point::Point(){} Point::Point(std::array<double, 3> theCoords){} Vector::Vector(std::array<double, 3> theComponents){} Axis::Axis(const Point& thePoint1, const Point& thePoint2){} Axis::Axis(const Point& thePassingPoint, const Vector& theDirectionVector){} Plane::Plane(const Point& thePoint1, const Point& thePoint2, const Point& thePoint3){} Plane::Plane(const Point& thePassingPoint, const Vector& theNormalVector){}
可以看到,各构造函数签名不同,仅Point类拥有默认构造函数。
注:仅Point类保留默认构造函数是出于物理合理性考虑——比如Vector不能全为零分量;若给其他类设置默认值(比如Plane默认设为全局坐标系xy平面),会依赖用户未知的Point和Vector对象,设计不佳;若设置默认构造函数生成不完整对象,则违反RAII原则。
当前API的问题
当前库没有统一API,用户需要按需引入各几何对象的头文件才能使用,示例代码如下:
#include<cs.hxx> #include<Point2D.hxx> #include<Point3D.hxx> #include<Vector2D.hxx> #include<Vector3D.hxx> #include<Axis.hxx> #include<LinePiece.hxx> #include<Circle.hxx> #include<Plane.hxx> int main() { Point3D point1 { Point3D(std::array<double, 3>{ 11., 12., 13. }) }; // Other objects }
期望的统一API
我希望通过统一接口访问库,若使用Creator类,用户代码可简化为:
#include<Creator.hxx> int main() { Point3D point1 { Creator::createPoint3D(std::array<double, 3>{ 11., 12., 13. }) }; // OR with a builder for example Builder builder = Builder("Point3D", std::array<double, 3>{ 11., 12., 13. }); // Just an example GeometryObject point2 { Creator::create(builder) }; // Other objects }
因此我计划创建一个Creator类作为库的统一API,拟采用静态创建函数简化实现,具体设计依赖于创建型设计模式(如抽象工厂、工厂方法、建造者等)。
Creator类的初步定义有两种思路:
第一种:
class Creator { static GeometryObject create(...); }
第二种:
class Builder { Builder(...); } class Creator2 { static GeometryObject create(const Builder&); }
现有方案的耦合痛点
直接的解决方案是为每个构造函数创建对应的静态成员函数,示例如下:
class Creator { static Axis createAxis(const Point& thePoint1, const Point& thePoint2); static Axis createAxis(const Point& thePassingPoint, const Vector& theDirectionVector); }
但这种实现会导致Creator类与库实现强耦合——库的任何变更(如新增构造函数)都需同步修改Creator类。我研究过抽象工厂、工厂方法和建造者模式,理解Creator类应独立于待创建类的定义,但无法解决构造函数签名各异的问题。
核心问题
- 采用创建型模式作为统一API是否合理?
- 如何构建与几何库实现解耦的
Creator类? - 应选用哪种设计模式?
内容的提问来源于stack exchange,提问作者Baris
相关产品推荐
相关产品推荐

