我想在 Delphi XE5 中创建一个三角网格结构。
主 TMyMesh 类具有通用 TObjectLists 来保存顶点、面等的列表。
假设我必须为网格的每个面计算一些东西。我可以让 TMyMesh 类处理这个:
TMyVertex=class(TComponent)
Vertex: TPoint3D;
//other fields and methods
end;
TMyTriangleFace=class(TComponent)
Vertices: Array [0..2] of Integer;
//other fields and methods
end;
TMyMesh=class(TComponent)
ListOfVertices: TObjectList<TMyVertex>;
ListOfTriangleFaces: TObjectList<TMyTriangleFace>;
procedure CreateListOfTriangleFaces;
procedure DoSomethingWithTheFace(const FaceNumber: Integer);
procedure DoSomethingWithAllFaces;
end;
procedure TMyMesh.CreateListOfTriangleFaces;
begin
for i := 0 to NumberOfTriangleFaces-1 do
begin
ListOfTriangleFaces.Add(TMyTraingleFace.Add(nil));
end;
end;
procedure TMyMesh.DoSomethingWithTheFace(const AFaceNumber: Integer);
begin
AVertex:=ListOfVertices[ListOfFaces[AFaceNumber].Vertices[0]];
//do something
end;
procedure TMyMesh.DoSomethingWithAllFaces;
begin
for i := 0 to ListOfFaces.Count-1 do
begin
DoSomethingWithTheFace(i);
end;
end;
或者我可以将它委托给 TMyTriangleFace 类:
TMyVertex=class(TComponent)
Vertex: TPoint3D;
//other fields and methods
end;
TMyTriangleFace=class(TComponent)
Vertices: Array [0..2] of Integer;
procedure DoSomethingWithTheFace;
//other fields and methods
end;
TMyMesh=class(TComponent)
ListOfVertices: TObjectList<TMyVertex>;
ListOfTriangleFaces: TObjectList<TMyTriangleFace>;
procedure CreateListOfTriangleFaces;
procedure DoSomethingWithAllFaces;
end;
procedure TMyTriangleFace.DoSomethingWithTheFace;
begin
AVertex:=TMyMesh(Owner).ListOfVertices[Vertices[0]];
//do something
end;
procedure TMyMesh.CreateListOfTriangleFaces;
begin
for i := 0 to NumberOfTriangleFaces-1 do
begin
ListOfTriangleFaces.Add(TMyTraingleFace.Add(Self));
end;
end;
procedure TMyMesh.DoSomethingWithAllFaces;
begin
for i := 0 to ListOfFaces.Count-1 do
begin
ListOfTriangleFaces[i].DoSomethingWithTheFace;
end;
end;
在这种情况下,我需要让 TMyTriangleFace 类访问 ListOfVertices。我可以通过在过程 CreateListOfTriangleFaces 中将 TMyMesh 作为所有者传递来做到这一点。
在我的理解中,第二部分应该是更好的代码(得墨忒耳法则)。但是作为所有者传递 TMyMesh 可能不是那么好。
这样做的最佳做法是什么?也许这两种解决方案都朝着错误的方向发展,并且有更好的解决方案?
非常感谢你!