避免基于节点的文件类型的文件导出器中的依赖地狱

Avoiding dependency hell in file exporter for node based file type?

本文关键字:文件 类型 地狱 依赖 于节点 节点      更新时间:2023-10-16

我正在努力为我正在编写的VRML文件导出器提出适当的设计模式。典型的VRML文件具有如下层次结构:

Transform {
translation 0 0 100
    children [
        Shape { 
            appearance Appearance { 
                texture ImageTexture { 
                    repeatS TRUE 
                    repeatT TRUE 
                    url [ 
                        "texture.png" 
                    ] 
                } # end texture 
            } # end appearance 
            geometry IndexedFaceSet { 
                normalPerVertex TRUE 
                solid TRUE 
                coord Coordinate { 
                    point [ 
                        -5.400000 0.030000 -0.000000,
                        ...
                    ]  # end point 
                } # end coord 
                texCoord TextureCoordinate { 
                    point [ 
                        0.062500 0.086207,
                        ...
                    ]  # end point 
                } # end texCoord 

        normal Normal {
            vector [
                0 1 0,
            ]
        } # end normals
                coordIndex [ 
                    0, 1, 2, -1,
                    ...
                ] # end coordIndex 
                texCoordIndex [ 
                    0, 1, 2, -1,
                    ...
                ] # end texCoordIndex 
                normalIndex [ 
                    0, 0, 0, -1,
                    ...
                ] # end normalIndex 
            } # end geometry 
        } # end shape 
    ] # end children
} # end Transform 

现在我继承自一个名为 Node 的基类,该基类具有基本的开始/结束字符串。不过,这开始产生依赖地狱。下面是一个示例:

#include "IndexedFaceSetNode.h"
#include "TextureCoodinateNode.h"
#include "NormalNode.h"
struct GeometryNode : Node 
{
    IndexedFaceSetNode* indexedFaceSet;
    TextureCoordinateNode textureCoordinate;
    NormalNode normal;
    GeometryNode(string isNormalNodePerVertex, string isSolid, vector<float> coordinates, vector<int> ind) :
    Node("tGeometryNode IndexedFaceSet { n",
        "t}n")
    {
        indexedFaceSet = new IndexedFaceSetNode(isNormalNodePerVertex, isSolid, coordinates, ind);
    }
};

我能做些什么呢?我可以使用更好的模式或 OOP 结构吗?

您应该仔细查看复合模式

它对于构建树结构很有用,并允许通过使用公共抽象以相同的方式处理分支和叶组件。

您可以使用像 Node(在模式上下文中也称为组件)这样的常见抽象,以便统一处理 GeometryNode 类中的所有子元素。

因此,您必须通过重写方法(可能使用运行时检查和强制转换)来使用多态性,以便执行特定行为。

有几种变体具有不同的优点和缺点。因此,我建议您在决定如何改进实现之前详细研究该模式。

例如,为了基本了解复合模式维基百科或更详细:复合图案演示