I have a small application which allows users to create accounts and then award 'points' to each other. UserAccount is an object, and so is Point, and there is an aggregation relationship between them: each UserAccount has a member variable (PointHistory) which is a collection of Points.
The Point object simply contains properties for which UserAccount object sent/received the Point.
This was fine when I simply serialized the classes to persist my object model. However, I am now implementing a database to persist the object data, and only one/some objects will be loaded into memory at any given time. To load the objects, I have a constructor method which creates a new UserAccount from a row in the database, and a similar constructor to create a Point from a database row. This is where the trouble starts - how can the constructor for one object call the constructor for another object when the second constructor must refer to what the first constructor has not yet constructed? In order to complete construction, the object must be already constructed.
开发者_如何学GoThe easy solution is simply to replace the collection of Point objects (PointHistory) with a collection of strings drawn from a database query. This suffices for my purposes. However, I'm wondering if there is another way to do that which doesn't abandon the Point object/object-model, and whether this aggregation/persistence problem is common?
If I understand correctly, the UserAccount constructor needs to construct the Points that belong to this UserAccount, and these Points need a way to refer to the UserAccount currently under construction?
If that is the case, you can pass Me into the Point constructor, which will in effect pass the UserAccount that's being constructed. It will pass the UserAccount object even it the construction hasn't yet completed.
Class UserAccount
Private _pointHistory As New System.Collections.Generic.List(Of MyProject.Point)
Public Sub New()
...
...
' Instantiate a new point, and pass this UserAccount object into it
' so that it can grab a reference
Dim newPoint as New MyProject.Point(Me)
'Add the Point to this UserAccount's collection
_pointHistory.Add(newPoint)
End Sub
End Class
Class Point
Private _parentAccount as MyProject.UserAccount
Public Sub New(parentAccount as MyProject.UserAccount)
'Store the reference to the User Account
_parentAccount = parentAccount
End Sub
End Class
精彩评论