我做了一個例子。代表其他對象的對象集合的面向對象設計
我有一類這個類的
class Person
{
//stuff
}
對象用在這裏和那裏等,但我會喜歡做單獨的類,這將是負責繪製者。所以我需要例如。屏幕上的Person
對象的位置。
我可以從Person
繼承:
class PersonVis : Person
{
Point location;
}
但我不知道PersonVis
應該有「是」與Person
關係。
我可以做一個字典,Person
關鍵和PersonProperties
爲值:
class PersonProperties
{
Point location;
}
但是我有一個情況,其中PersonProperties
類的屬性一個取決於Person
狀態,所以也許不是使用字典,我應該使用只是一個列表:
class PersonProperties
{
Person person;
Point location;
}
但如果我這樣做,我必須非常小心插入的PersonProperties
新對象到該列表時,因爲我最終可能會得到兩個內部具有相同Person
實例的對象。
在您看來,最佳選擇是什麼?
編輯
我想我必須拿出真實的例子。
我有類Graph
class Graph
{
List<Vertex> Vertices;
//other stuff
}
class Vertex
{
//stuff not related to drawing at all
}
我使用這個類來解決問題。我根本不需要圖形表示,我不需要例如頂點的位置。
現在我創建的類繪製此圖:
class GraphDrawer
{
Graph GraphToDraw;
XXX xxx;
void OnDraw()
{
//use vertices from graph, but use also stored positions of the vertices
//and any other things related to drawing
}
}
頂點例如可以是。移動,因此繪圖更改和圖形的屬性必須重繪。
XXX是保存關於例如信息的結構。當前點的頂點。
我不知道我應該選擇什麼樣的XXX。
XXX可能是:Dictionary<Vertex, VertexProperties>
其中VertexProperties
:
class VertexProperties
{
Point location;
}
但是我有一個情況,其中VertexProperties
類的屬性一個取決於Vertex
狀態。因此,也許List<VertexProperties>
其中VertexProperties
:
class VertexProperties
{
Vertex vertex;
Point location;
}
但如果我這樣做,插入的VertexProperties
新對象到該列表時,我必須非常小心,因爲我可以用裏面的相同Vertex
實例的兩個對象結束。
也許List<VertexVis>
其中VertexVis
:
class VertexVis : Vertex
{
Point location;
}
但是,這是相同以前+我不覺得VertexVis
「是」 Vertex
。
是的,我今天想知道它,現在正在實施它。我決定有例如。 'Vertex'對象和子類:'DrawableVertex'帶有附加字段。該視圖將得到'DrawableGraph'。我正在使用C#,所以我決定有'Graph其中T:Vertex'和'DrawableGraph:Graph '(我忽略了邊)。我不知道這是不是個好主意,但現在代碼看起來更清晰。 –
prostynick
2010-06-23 17:17:12